Could not link C ++ exe with C library (GNU)

I've created a simple simple code to illustrate my problem.

header.h:

#ifdef __cplusplus
#   define API extern "C"
#else
#   define API
#endif

void callback();
API void libFunction();

      

testlib.c:

#include "header.h"

void libFunction()
{
    Callback();
}

      

I am compiling this as a static library like this:

gcc -c testlib.c
ar rsc libtest.a testlib.o

      

Then my C ++ code example is

main.cpp:

extern  "C"{
#include  <lib/header.h>
}
#include  <stdio.h>

main()
{
    libFunction();
}

void Callback()
{
    printf("Callback is called \n");
}

      

and i am trying to build my exe as such

g++ -I. -L. main.cpp -ltest

      

and get the following error

./lib/libtest.a(testlib.o): In function `libFunction':
testlib.c:(.text+0x7): undefined reference to `Callback'
collect2: ld returned 1 exit status

      

I spent literally all day trying to figure out why. Can anyone please help?

+3


source to share


1 answer


If you want to call Callback

from a C file, it must be created extern "C"

in your C ++ file, otherwise, if the C ++ name is changed, the characters will not match. You have to change the definition Callback()

in main.cpp

the following way:

extern "C" void Callback()

      



You also have a mismatch in the case. The prototype in your title says Callback

, but everywhere you use Callback

. Upon re-reading the code, I think that only fixing this inconsistency can solve all your problems. I didn't see the wrapper extern "C"

around #include <lib/header.h>

on first reading.

+3


source







All Articles