Alex
Alex

Reputation: 2040

C/C++ duplicate symbols error

I'm currently trying to compile an existing project which is a mix of cpp and c.

My makefile is as follows;

execute: mgnsvd.o multifit.o cit.o  main.o
    g++ -Wall -g multifit.o cit.o main.o mgnsvd.o -lgsl -lgslcblas -o execute 

main.o: main.cpp cit.cpp
    g++ -Wall -g -c main.cpp

cit.o: cit.cpp mgnsvd.c multifit.h
   g++ -Wall -g -c cit.cpp

multifit.o: multifit.c mgnsvd.c multifit.h
   g++ -Wall -g -c multifit.c

mgnsvd.o: mgnsvd.c
    g++ -Wall -g -c mgnsvd.c

And my main is a rather plain

// global libraries
#include <iostream>

// local files
#include "cit.cpp"

// using directives
using std::endl;
using std::cout;

// main
int main(){

  cout << "Hello, world" << endl; 

 return 0;
}

If is comment out #include "cit.cpp" it compiles fine. However, if i include it the following error happens;

ld: duplicate symbol _first_function_in_cit in main.o and cit.o for architecture x86_64

_first_function is always the first function, and is not defined or even declared/used anywhere else. A grep of the object files confirms the function seems to be incorporated into main.o, but why? I've not worked on a C++/C project before, so maybe I'm making some canonical error? I'm also in OSX, if that makes a difference.

For the record, there are no classes - the .h file contains a few structs and some macros.

Upvotes: 1

Views: 5370

Answers (3)

David Hammen
David Hammen

Reputation: 33126

YOu are compiling cit.cpp to yield cit.o, and you are compiling it again with that #include "cit.cpp" attrocity in your main.cpp. So of course you are getting duplicate symbols.

Upvotes: 2

Mark Ransom
Mark Ransom

Reputation: 308206

cit.cpp is being compiled by itself, and is also included in main.cpp so you're getting two copies of all the code in it.

Upvotes: 4

stefan bachert
stefan bachert

Reputation: 9608

There is no need for

 #include "cit.cpp"

cit.cpp is compiled as a separate unit and later linked.

With the above include you get the code twice with results in duplicate symbols

Upvotes: 4

Related Questions