1

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 totest_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??

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried that but didn't work. in this case both are c files but the executable is making with g++ compiler
1

As Dirk said, change extern int test_init(); to extern "C" { int test_init(); }

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.