Victor.dMdB Victor.dMdB - 2 months ago 5x
C Question

"Undefined reference to" Error while linking object files

I realise this question has been asked in a number of ways including this very comprehensive answer but I have looked at many and tried fixing my error to no avail.

I am using .cpp and .c files to create a program. I compiled all files with g++, it seemed to have no more linking errors, though it gave me a bunch of C++ errors related to the C syntax. This was the command I used:

g++ -o program main.cpp /data/*.c -l[...libs]

The main.cpp calls functions in the .c files.
I then understood that one should not try to compile both .c and .cpp files with one compiler, instead to use gcc for one, g++ for the other, and thereafter to simply link the object files.

So I did this (the .c files are part of a library, and already have .o files)

g++ -c main.cpp
g++ -o program main.o /data/*.o -l[..libs]

But then here I will get "undefined reference to" errors for functions called from main.cpp to the precompiled .c files, errors which I didn't get previously.

Could anyone help? Or do I maybe need to provide more information?

EDIT (a more in depth excerpt of code, I've tried to simplify otherwise this will be impossible to read, but let me know if I still need to add stuff, I'll try to remove unnecessary code):

main.cpp :

#include "header.h"

int main(int argc, char** argv) {
string s1 = argv[2];


void fn1(string s1)

#include "header1.h"

void fn1(string s1){
fprintf(stdout, " you entered %s", s1);


@Smeehey helped me figure out the solution, it was actually that I was still including the old headers in an .hpp file I was using. But the core solution was indeed to use the external C{}.


This is highly likely to do with C-vs-C++ linkage. In your main.cpp, you probably have something like this:

#include <data/header.h>

where header.h refers to your c library. Replace it as follows:

extern "C" {
#include <data/header.h>

This tells your c++ compiler not to use c++-style name mangling when defining the required symbols from the header, allowing the linker to successfully find them in the c-compiled .o files.