PJ_ PJ_ - 2 months ago 14
C++ Question

C++ Error on Neural Network Implementation: duplicate symbols for architecture x86_64

Hey guys I'm trying to implement the backpropagation algorithm in C++ and I've tried Xcode and C++ Eclipse but I'm getting the same error and I have no idea how to fix it, I've tried searching here but none of the proposed solution worked, here is the following error message and my code.

Error Message:

make all
Building file: ../src/NeuralNet.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++11 -MMD -MP -MF"src/NeuralNet.d" -MT"src/NeuralNet.d" -o"src/NeuralNet.o" "../src/NeuralNet.cpp"
Finished building: ../src/NeuralNet.cpp

Building target: NeuralNet
Invoking: MacOS X C++ Linker
g++ -o "NeuralNet" ./src/Net.o ./src/NeuralNet.o
duplicate symbol __ZN3NetC2ERKNSt3__16vectorIjNS0_9allocatorIjEEEE in:
./src/Net.o
./src/NeuralNet.o
duplicate symbol __ZN3NetC1ERKNSt3__16vectorIjNS0_9allocatorIjEEEE in:
./src/Net.o
./src/NeuralNet.o
ld: 2 duplicate symbols for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [NeuralNet] Error 1


And here is my code:

NeuralNet.cpp

#include <iostream>
#include <vector>
#include "Net.cpp"

using namespace std;

int main() {
vector<unsigned> topology;
topology.push_back(10);
Net net(topology);


return 0;
}


Net.h

#ifndef NET_H_
#define NET_H_

#include <vector>

using namespace std;

class Net {
public:
Net(const vector<unsigned>& topology);
};

#endif


Net.cpp

#include "Net.h"

Net::Net(const vector<unsigned>& topology) {
// TODO Auto-generated constructor stub

}

Answer

Your IDE is trying to compile both .cpp files as individual compilation units, because usually those contain the individual compilation units.

However you are including Net.cpp in NeuralNet.cpp, so the code in it (i.e. the implementation of Net::Net) is compiled in the unit of Net.cpp as well as the unit of NeuralNet.cpp.

After compiling both compilation units the linker is called to link them together. It notices that Net::Net appears twice and doesn't know which to choose, therefore the error.

You should never #include a .cpp file. Replace #include "Net.cpp" with #include "Net.h". You always include the header (.h) for the class, not the source (.cpp).