0

How do you link 2 c library files, to a c++ file?

Right now I am doing this:

> gcc -c file1.c (this works fine) 

> gcc -c file2.c ( this works fine)

> g++ -c myc++file.cpp (this works fine)

> g++ -o program myc++file.o file1.o file2.o

-> I get an error on this last one saying that their is a undefined reference to a function in myc++file.o, but that function is defined in file2.o. Something is wrong, but I just cant figure it out.

Any ideas?

bryan sammon
  • 7,161
  • 15
  • 38
  • 48

2 Answers2

3

Is this function static?

Did you use extern "C" in myc++file.cpp?

if the answers is no and yes, show us some code.

(By the way, try to check using nm if that function is really in file2.o)

asaelr
  • 5,438
  • 1
  • 16
  • 22
  • Technically both of you are right, thanks alot for the quick repsonse. I saw you responded first. For anyone else with this same problem, this answer is good, then also look at this link: http://stackoverflow.com/questions/3789340/combining-c-and-c-how-does-ifdef-cplusplus-work – bryan sammon Jan 29 '12 at 21:34
2

You need to use extern "C" on the function's declaration.
When C++ sees an external function, it mangles the name, to identify the parameter and return value types. When trying to link it with C code, the names don't match.
extern "C" tells C++ not to mangle the name, so it would successfully link with C code.

ugoren
  • 16,023
  • 3
  • 35
  • 65