PJ_ PJ_ - 1 year ago 111
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:
duplicate symbol __ZN3NetC1ERKNSt3__16vectorIjNS0_9allocatorIjEEEE in:
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:


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

using namespace std;

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

return 0;


#ifndef NET_H_
#define NET_H_

#include <vector>

using namespace std;

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



#include "Net.h"

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


Answer Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download