How do I source/link external functions in C or C++?

前端 未结 3 436
天涯浪人
天涯浪人 2021-02-04 21:57

EDIT: I suppose I should clarify, in case it matters. I am on a AIX Unix box, so I am using VAC compilers - no gnu compilers. End edit

<
3条回答
  •  清酒与你
    2021-02-04 22:32

    Yeah you are correct. The first is called a static library, while the second is called a shared library, because the code is not bound to the executable at compile time, but everytime again when your program is loaded.

    Static library

    Compile your library's code as follows:

    gcc -c *.c
    

    The -c tells the program not to link the object file, but just leaves you with object files for each .c file that was compiled. Now, archive them into one static library:

    ar rcs libmystuff.a *.o 
    

    man ar will tell you what the rcs options mean. Now, libmystuff.a is a archive file (you can open it with some zip-file viewers) which contain those object files, together with an index of symbols for each object file. You can link it to your program:

    gcc *.c libmystuff.a -o myprogram
    

    Now, your program is ready. Note that the order of where the static libraries appear in the command matter. See my Link order answer.

    Shared library

    For a shared library, you will create your library with

    gcc -shared -o libmystuff.so *.c
    

    That's all it takes, libmystuff.so is now a shared object file. If you want to link a program to it, you have to put it into a directory that is listed in the /etc/ld.so.conf file, or that is given by the -L switch to GCC, or listed in the LD_LIBRARY_PATH variable. When linking, you cut the lib prefix and .so suffix from the library name you tell gcc.

    gcc -L. -lmystuff *.c -o myprogram
    

    Internally, gcc will just pass your arguments to the GNU linker. You can see what arguments it pass using the -### option: Gcc will print the exact arguments given to each sub process.

    For details about the linking process (how some stuff is done internally), view my Linux GCC linker answer.

提交回复
热议问题