简体   繁体   中英

gcc compiling and linking

I created a shared library in this way

gcc -I/home/lib 'pkg-config --cflags gtk+-2.0 libxml-2.0' -shared -fPIC -Wl,--export-dynamic file1.c file2.c -o lib.so

it works and the library created also works for what I need. What I want to know is where the compiling and the linking are in this command string, so please explain it to me and tell me a way to divide them in two different commands, just to understand better. I need to understand this because I can't not explain why this library works, even if this has to be linked to another one that I've never linked to it.

The gcc -c option is for compile only. However, I'm not sure if that is what you want.

Your command compiles and links in one invocation.

You can split the command into compiling and linking commands:

gcc -c -o file1.o -Wall -Wextra -Werror -I/home/lib $(pkg-config --cflags gtk+-2.0 libxml-2.0) -fPIC file1.c
gcc -c -o file2.o -Wall -Wextra -Werror -I/home/lib $(pkg-config --cflags gtk+-2.0 libxml-2.0) -fPIC file2.c
gcc -shared -o lib.so file1.o file2.o

GCC uses the extensions in the file names to determine what type they are and what to do with them. So the fact that you listed some names ending with “.c” tells GCC to compile them as C code. If you had given only names ending with “.o”, GCC would treat them as object files and would not compile them.

After compiling, GCC by default links to make an executable. The “-shared” switch tells it to make a shared library instead.

To compile only, without linking, you could use the switch “-c” and remove the “-shared” switch, and also remove any of the command arguments or switches that are only used for linking (“-Wl,--export-dynamic” is one, and I do not know whether that pkg-config will produce any link options). Also remove or change the “-o lib.so”, since that sets the name to use for the output file, and it is not what you want for object files that result from compiling only.

To link only, without compiling, you would simply list object files instead of source files and remove the switches affecting compilation (“-I/home/lib”, “-fPIC”, and any produced by pkg-config).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM