简体   繁体   中英

linker delets library and does not recognize it

I am compiling a C program with g++ and linking it to a library mylib.lib which is located in the same folder as the sourcecode by:

user$ g++ myprog.c -o mylib.lib

and the compiler behaves in a strange way. first of all it gives the error 'undefined reference to fun1' . this should not happen because fun1 is in mylib.lib. secondly it deletes mylib.lib . I also tried a different way:

user$ g++ myprog.c mylib.lib

In this case I get the same error: 'undefined reference to fun1' Finally I tried to add mylib by:

  1. renamed mylib.lib to libmylib.lib

2.

user$ g++ myprog.c -L/Dima/Tests -l mylib

In this case the error is 'cannot find lmylib' although it is located in /Dima/Tests. how do I compile it correctly?

You're not building a library, you are trying to create an executable program named mylib.lib . That's why the linker is invoked.

If you want to create a library, it depends on the toolchain you target, but generally speaking you only create object files, and create an archive of those object files.

For the GNU toolchain (GCC and the GNU binutils linker) you use the ar program to create this archive.

$ g++ mylib.c -c             # Create object file named `mylib.o`
$ ar crv libmylib.a mylib.o  # Create the static library

Now you have a static library containing the object file myprog.o which is compiled from myprog.c . To use it do something like

$ g++ myprog.c -L. -lmylib -o myprog

The above command tells the linker to look in the current directory ( -L. ) and link with the library mylib (the linker automatically looks for libmylib.a ).

Also, when using the GNU linker it's important that you put the libraries after any source or object files.

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