phuong
phuong

Reputation: 293

/usr/bin/C++ not compile as gcc with Shared library

I try to work on shared library.

In detail, I following this link: http://www.cprogramming.com/tutorial/shared-libraries-linux-gcc.html.

Everything ok with this command:

$ gcc -L/home/user/foo -Wl,-rpath=/home/user/foo -Wall -o test main.c -lfoo
$ ./test

But when i change from gcc to /usr/bin/c++, ANd change commands to:

$ /usr/bin/c++ -L/home/user/foo -Wl,-rpath=/home/user/foo -Wall -o test2 main.c -lfoo
/tmp/ccpEHbNV.o: In function `main':
main.c:(.text+0x16): undefined reference to `foo()'
collect2: error: ld returned 1 exit status

It can't find the method foo in my libfoo.so.

I also try by another way with -rdynamic, It also work well with gcc:

gcc -rdynamic ./libfoo.so -Wl,-rpath=/home/user/foo -Wall -o test main.c -lfoo

But It also have the same error with /usr/bin/c++.

Please show me how to make it work with /usr/bin/c++.

Thank a lot.

Upvotes: 0

Views: 1532

Answers (3)

strikr
strikr

Reputation: 1

What is the version of gcc and c++ you are using ?

Ideally within the same compiler tool-chain family there should be no error.

In fact, i wrote the code, compiled and executed the same example without any issues.

Please note the version of gcc/c++ i am using.

gcc (GCC) 6.2.1 20160830
g++ (GCC) 6.2.1 20160830

i wrote a shell script file to execute the commands

strace c++ -c -Wall -Werror -fpic foo.c
strace c++ -shared -o libfoo.so foo.o
strace c++ -L. -Wall -o test main.c -lfoo

and collected the strace output of the compilation and linking. Please see the link below http://pastebin.com/nJpQuCfS

Hope this helps.

Upvotes: -1

e.jahandar
e.jahandar

Reputation: 1763

As others said, this is because different symbol naming between C and C++ compiled libraries, As C++ have overloaded functions the naming for each symbol should include type of arguments in symbol name or something which identifies the actual function or class method based on its arguments. Unlike C++, C doesn't have this issue, because of no function overloading and its standard ABI. if you want mix C/C++ files you have to compile all the C & C++ codes with g++ and also add extern C keyword to definition of C codes

#ifdef __cplusplus
extern "C" {
#endif

// your C definitions (only function definitions) goes here

#ifdef __cplusplus
}
#endif

Upvotes: 2

shiv
shiv

Reputation: 1952

The problem is coming probably because of name mangling of C++. /usr/bin/c++ ends up as /usr/bin/g++. gcc is a C compiler while g++ is a C++ compiler. You need to compile your library libfoo.so with g++ and then try to link. It should work.

Upvotes: 1

Related Questions