Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Link .so file to .cpp file via g++ compiling

Tags:

c++

linux

i am trying to get a library to work in my c++ project and there is no clear instructions of how to do this for people who are not used to c++

the following link is the closest i have come

it states the following

-L/path/to/my/library/folder -ldllname

also the following thread states the following

gcc yourfile.cpp -lblah

now from what i can see the command is -l + filename, for example my filename is directory/libtest.so it would be -ldirectory/libtest.so, is this correct, could someone clarify

i am currently using the following command to compile my maincpp.cpp file, would like to however include a .so file called for example ./directory/libtest.so

g++ -fPIC -o libgetmacip.so -shared -I $JAVA_HOME/include -I $JAVA_HOME/include/linux maincpp.cpp cpptoinclude.cpp
like image 783
basickarl Avatar asked Nov 30 '14 01:11

basickarl


People also ask

How do I link two sources in CPP?

Basically linking or including is done by #include<filename> or #include”filename” in C++. Now, as per your question, two c++ files can be linked by using #include”filename. cpp” , if all the files are in same directory. Otherwise specify the directory name before the filename.

Can gcc compile C++ files?

GCC stands for GNU Compiler Collections which is used to compile mainly C and C++ language. It can also be used to compile Objective C and Objective C++.


1 Answers

now from what i can see the command is -l + filename, for example my filename is directory/libtest.so it would be -ldirectory/libtest.so

No, that's not correct. It should be -Ldirectory -ltest i.e. you use -L to add a directory to the search paths where the linker will look for libraries, and you say which libraries to link to with -l, but to link to libtest.so or libtest.a you say -ltest without the lib prefix or the file extension.

You can link by naming the file explicitly, without -L or -l options, i.e. just directory/libtest.so, but for dynamic libraries that is almost always the wrong thing to do, as it embeds that exact path into the executable, so the same library must be in the same place when the program runs. You typically want to link to it by name (not path) so that the library with that name can be used from any location at run-time.

like image 128
Jonathan Wakely Avatar answered Sep 24 '22 17:09

Jonathan Wakely