Reputation: 11
I made shared library using gcc . I would like to link this library using g++ comiler with source code *.c. Example
test_init.c
#include<stdio.h>
int test_init()
{
printf(" test init success\n");
return 0;
}
gcc -shared -o libtest.so test_init.c
test.c
#include<stdio.h>
extern int test_init();
main()
{
test_init();
}
g++ -I. -L. -ltest test.c
/tmp/ccuH5tIO.o: In function
main': test.c:(.text+0x7): undefined reference to
test_init()' collect2: ld returned 1 exit status
Note: If i compile test.c with gcc it works, but i would like to use this approach due to other dependencies. Is it possible??
Upvotes: 1
Views: 3546
Reputation: 15734
Usually -llibrary
should be after object files or c/c++ files in gcc command line
g++ -I. -L. test.c -ltest
The linker searches for the symbols mentioned in test.c after it's processed and when you put -llib
before test.c, it's just unable to find them.
See man ld
for more info.
Not sure how the things are when you use extern
, perhaps something is different in this case.
Upvotes: 1
Reputation: 91260
As Dirk said, change extern int test_init();
to extern "C" { int test_init(); }
Upvotes: 1
Reputation: 368181
You call C routines from C++ by declaring them
extern "C" {
....
}
Look into a few header files on your system or Google around -- that's the only way to do it because of different function signature systems between the languages.
Upvotes: 1