简体   繁体   中英

Is the GCC link option truly necessary when linking to a static library?

I've been playing around with GCC lately and have been experimenting with the linking options. I'm somewhat confused why the link option -l is necessary when statically linking to an archive file. It seems like you can just toss the.a file as if it were an ordinary object file.

For example, take the following make file:

test1 : main.c libfunc.a
    gcc main.c -L. -lfunc -o main.out

test2 : main.c libfunc.a
    gcc main.c libfunc.a -o main.out

libfunc.a : func1.c func2.c
    gcc func1.c -c
    gcc func2.c -c
    ar cr libfunc.a func1.o func2.o

Make target test1 uses GCC's linking options to link to the archive file. Target test2 instead just includes the archive file direct. Building and running each output seem to result in the same executable.

There are several ways you can tell gcc what file(s) to use. An argument of the form -l name (or the two arguments -l name ) says “Search for a library named name ”. Per the GCC documentation , this argument is passed to the linker (typically the ld command). The linker looks for a file with a name like lib name . extension lib name . extension , where extension is one of the known library files extensions such as .a or .so , and it looks for files with those names in a list of library directories it has. You can add directories to search with the -L switch.

When the linker finds the library, it uses it just as if you had specified the path, so the end result is the same whether you specify the library with -l or with its path.

By using the path, you can specify libraries that are not in the known library directories or that have unusual names.

Note that the linker does not process libraries the same way as object files. When the linker processes an object file, it incorporates everything in the object file into the output file being constructed. When the linker processes a library file, it incorporates only those modules within the library that provide a symbol definition for a symbol referenced by a prior module and not yet resolved. For example, if you write a program that uses sqrt but does not use sin , then, when the linker processes libm.a after reading your object module, it will take the sqrt module from the library but not the sin module.

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