C++ 编译独立的静态可执行文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3283021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compile a Standalone Static Executable
提问by Dan Snyder
I'm trying to compile an executable (ELF file) that does not use a dynamic loader. I built a cross compiler that compiles mips from linux to be used on a simulator I made. I asserted the flag -static-libgcc on compilation of my hello.cpp file (hello world program). Apparently this is not enough though. Because there is still a segment in my executable which contains the name/path of the dynamic loader. What flags do I use to generate an executable which contains EVERYTHING needed to be run? Do I need to rebuild my cross compiler?
我正在尝试编译一个不使用动态加载程序的可执行文件(ELF 文件)。我构建了一个交叉编译器,它从 linux 编译 mips 以在我制作的模拟器上使用。我在编译 hello.cpp 文件(hello world 程序)时声明了标志 -static-libgcc。显然这还不够。因为我的可执行文件中仍有一个包含动态加载程序名称/路径的段。我使用什么标志来生成包含需要运行的所有内容的可执行文件?我需要重建我的交叉编译器吗?
采纳答案by sigjuice
Try using the -static
flag?
尝试使用-static
标志?
回答by Bernhard Kausler
Use the following flags for linking
使用以下标志进行链接
-static -static-libgcc -static-libstdc++
Use these three flags to link against the static versions of all dependencies (assuming gcc). Note, that in certain situation you don't necessarily need all three flags, but they don't "hurt" either. Therefore just turn on all three.
使用这三个标志来链接所有依赖项的静态版本(假设是 gcc)。请注意,在某些情况下,您不一定需要所有三个标志,但它们也不会“伤害”。因此,只需打开所有三个。
Check if it actually worked
检查它是否真的有效
Make sure that there is really no dynamic linkage
ldd yourexecutable
should return "not a dynamic executable" or something equivalent.
Make sure that there are no unresolved symbols left
nm yourexecutable | grep " U "
The list should be empty or should contain only some special kernel-space symbols like
U __tls_get_addr
Finally, check if you can actually execute your executable
确保确实没有动态链接
ldd yourexecutable
应该返回“不是动态可执行文件”或等效的东西。
确保没有留下未解析的符号
nm yourexecutable | grep " U "
该列表应该是空的或者应该只包含一些特殊的内核空间符号,比如
U __tls_get_addr
最后,检查您是否可以真正执行您的可执行文件