[英]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: 我正在使用g ++编译C程序,并将其链接到库mylib.lib,该库位于与源代码相同的文件夹中,方法是:
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' .
首先,它给出错误“对fun1的未定义引用”。 this should not happen because fun1 is in mylib.lib.
这不会发生,因为fun1在mylib.lib中。 secondly it deletes mylib.lib .
其次,它删除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: 在这种情况下,我会得到相同的错误:“对fun1的未定义引用”最后,我尝试通过以下方式添加mylib:
2. 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. 在这种情况下,尽管位于/ Dima / Tests中,但错误为“找不到lmylib”。 how do I compile it correctly?
如何正确编译?
You're not building a library, you are trying to create an executable program named mylib.lib
. 您不是在构建库,而是在尝试创建名为
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. 对于GNU工具链(GCC和GNU binutils链接器),您可以使用
ar
程序创建此归档文件。
$ 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
. 现在你有一个包含目标文件中的静态库
myprog.o
是从编译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
). 上面的命令告诉链接器在当前目录(
-L.
)中查找并与库mylib
链接(链接器自动查找libmylib.a
)。
Also, when using the GNU linker it's important that you put the libraries after any source or object files. 同样,在使用GNU链接器时,将库放在任何源文件或目标文件之后也很重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.