[英]How to write a static C++ library and link it to an executable using g++ on Windows 10?
主程序
#include <iostream>
int main() {
std::cout << "main()" << std::endl;
foo();
return 0;
}
文件
#include <iostream>
extern "C" {
void foo() {
std::cout << "bar" << std::endl;
}
}
编译静态库:
$ g++ foo.cpp -static
错误:
undefined reference to `WinMain'
但这编译:
$ g++ foo.cpp -shared -o foo.lib
现在我有一个名为foo.lib
的静态库(据说)。
我尝试编译一个链接到它的可执行文件:
$ g++ -L -lfoo main.cpp -o main.exe
并得到这个错误:
'foo' was not declared in this scope
但是foo
是在我链接的静态库中声明的。 如果链接有效,我认为我也不需要在main.cpp 中声明它。 那么为什么链接不起作用呢?
更新。
我添加了void foo();
到main.cpp所以它不会抱怨需要声明foo
。
#include <iostream>
void foo();
int main() {
std::cout << "main()" << std::endl;
foo();
return 0;
}
所以我尝试再次编译,但出现了这个新错误:
undefined reference to `foo()'
为什么我需要在main.cpp 中定义foo
? 它已经在foo.cpp中定义,它是静态库。
如果我必须在main.cpp中定义foo
这会破坏链接到库foo.lib的整个目的。
更新
extern "C" {
... }
行不会使“ foo
is undefined”错误消失。以下是您寻求的魔法咒语:
#include <iostream>
extern void foo();
int main() {
std::cout << "main()" << std::endl;
foo();
}
#include <iostream>
void foo() {
std::cout << "bar" << std::endl;
}
控制台命令:
$ g++ -o foo.obj -c foo.cpp
$ ar rcs foo.lib foo.obj
$ g++ main.cpp foo.lib -o main.exe
这些咒语让人联想到静态库foo和静态链接到它的可执行文件main 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.