简体   繁体   English

如何使用g ++创建静态库?

[英]How to create a static library with g++?

Can someone please tell me how to create a static library from a .cpp and a .hpp file? 有人可以告诉我如何从.cpp和.hpp文件创建静态库吗? Do I need to create the .o and the .a? 我需要创建.o和.a吗? I would also like to know how can I compile a static library in and use it in other .cpp code. 我还想知道如何在其中编译静态库并在其他.cpp代码中使用它。 I have header.cpp , header.hpp . 我有header.cppheader.hpp . I would like to create header.a . 我想创建header.a Test the header.a in test.cpp . test.cpp测试header.a。 I am using g++ for compiling. 我正在使用g ++进行编译。

Create a .o file: 创建一个.o文件:

g++ -c header.cpp

add this file to a library, creating library if necessary: 将此文件添加到库中,如有必要,创建库:

ar rvs header.a header.o

use library: 使用库:

g++ main.cpp header.a

You can create a .a file using the ar utility, like so: 您可以使用ar实用程序创建.a文件,如下所示:

ar crf lib/libHeader.a header.o

lib is a directory that contains all your libraries. lib是包含所有库的目录。 it is good practice to organise your code this way and separate the code and the object files. 最好以这种方式组织代码并将代码和目标文件分开。 Having everything in one directory generally looks ugly. 将所有内容放在一个目录中通常看起来很丑。 The above line creates libHeader.a in the directory lib . 上一行在lib目录中创建libHeader.a So, in your current directory, do: 因此,在当前目录中,执行以下操作:

mkdir lib

Then run the above ar command. 然后运行上面的ar命令。

When linking all libraries, you can do it like so: 链接所有库时,可以这样进行:

g++ test.o -L./lib -lHeader -o test  

The -L flag will get g++ to add the lib/ directory to the path. -L标志将使g++lib/目录添加到路径。 This way, g++ knows what directory to search when looking for libHeader . 这样, g++在查找libHeader时知道要搜索的目录。 -llibHeader flags the specific library to link. -llibHeader标记要链接的特定库。

where test.o is created like so: 在哪里创建test.o像这样:

g++ -c test.cpp -o test.o 

Can someone please tell me how to create a static library from a .cpp and a .hpp file? 有人可以告诉我如何从.cpp和.hpp文件创建静态库吗? Do I need to create the .o and the the .a? 我需要创建.o和.a吗?

Yes. 是。

Create the .o (as per normal): 创建.o (按照常规):

g++ -c header.cpp

Create the archive : 创建档案

ar rvs header.a header.o

Test : 测试

g++ test.cpp header.a -o executable_name

Note that it seems a bit pointless to make an archive with just one module in it. 请注意,仅使用一个模块进行归档似乎没有意义。 You could just as easily have written: 您可以很容易地写出:

g++ test.cpp header.cpp -o executable_name

Still, I'll give you the benefit of the doubt that your actual use case is a bit more complex, with more modules. 尽管如此,我还是会给您带来疑问的好处,那就是您的实际用例会更复杂,带有更多的模块。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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