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

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.


This is a step by step procedure of how to create and link a .so with .cpp file

  1. Create .cpp file that you want to convert to .so.
    Example -
    #include<stdio.h> int add(int a , int b) { return a+b;}

    Save it by name add.cpp

  2. Create .so with following command
    gcc -c -fPIC add.cpp -o add.o

    This creates libadd.so

  3. Create a .cpp file which will use this .so file
    Example-
    #include<stdio.h> extern int add(int a, int b); int main(int argc, char** argv) { printf("Hello the output is %d \n",add(10,15)); return 0; }

    Save it as main_file.cpp

  4. Create a .o file from this file using this command
    g++ -c main_file.cpp

  5. Link .so with .o using this command
    g++ -o prog main_file.o -L. -ladd

    Here L specifies the folder with the .so file
    And -l specifies the name of the .so library

  6. Run the program with the command
    ./prog

Tags:

Linux

C++