链接静态库的多重定义错误

时间:2013-09-13 05:11:26

标签: c++ linker g++

编辑这个解决了: 问题是,即使我在编辑源文件后重建了库,但在重新尝试测试之前我没有删除库,而且那里有一些旧文件。

所以我有一个像这样设置的库

individual.h

#ifndef INDIVIDUAL_H
#define INDIVIDUAL_H
....
namespace dgal {
    class individual {
        public:
            individual() = delete;
            individual(const size_t numWeights);
            individual(const std::shared_ptr<dgal::individual> parentA, const std::shared_ptr<dgal::individual> parentB);
            ...
    };

}
#endif

individual.cpp

#include "individual.h"
...
dgal::individual::individual(const size_t numWeights) : weights(numWeights) {
    ...
}

dgal::individual::individual(const std::shared_ptr<dgal::individual> parentA, const std::shared_ptr<dgal::individual> parentB){
    ...
}

编译并放入静态库

构建测试的makefile就像这样

includes = -I../src/
LDLIBS = -L../build -ldgal -pthread
CXXFLAGS = -std=c++11 -Wall -Wextra $(includes)

all:
    $(CXX) $(CXXFLAGS) -o test.out main.cpp $(LDLIBS)
    @echo "Tests built"

和main.cpp看起来像:

...
class test : public dgal::individual {
    public:
        test() : dgal::individual(10) {std::cout << "test constructor" << std::endl;}
        test(const std::shared_ptr<dgal::individual> a, const std::shared_ptr<dgal::individual> b) : dgal::individual(a, b) {}
};

int main(){

    std::shared_ptr<test> A(new test);
    std::shared_ptr<test> B(new test);

    std::shared_ptr<test> C(new test(A,B));
    return 0;
}

但是我从g ++那里得到了关于我的dgal::individual::individual(unsigned long)的多重定义错误,这是我的size_t构造函数。但是,在我尝试使用test(const std::shared_ptr<dgal::individual> a, const std::shared_ptr<dgal::individual> b)构造函数之前,它没有出现错误,我不明白多个定义的来源。

编辑确切错误:

g++ -std=c++11 -Wall -Wextra -I../src/ -o test.out main.cpp -L../build -ldgal -pthread
../build/libdgal.a(individual.o): In function `dgal::individual::individual(unsigned long)':
individual.cpp:(.text+0x0): multiple definition of `dgal::individual::individual(unsigned long)'
../build/libdgal.a(individual.o):individual.cpp:(.text+0x0): first defined here
../build/libdgal.a(individual.o): In function `dgal::individual::individual(unsigned long)':
individual.cpp:(.text+0x0): multiple definition of `dgal::individual::individual(unsigned long)'
../build/libdgal.a(individual.o):individual.cpp:(.text+0x0): first defined here

如果我编辑默认构造函数不被删除并尝试使用默认构造函数而不是带有参数的构造函数,那么它工作正常并且不会抱怨多个定义

0 个答案:

没有答案