用ar编译存档,手动编译,ld找不到
Compiled archive with ar, compiles manually, ld does not find
我编译了一个 hello world 库来测试我的构建设置:
// hw.cpp
#include<iostream>
#include"hw.h"
void hw(){ std::cout << "hw"<<std::endl; }
// hw.h
void hw();
// main.cpp
#include"hw.h"
int main(int argv, char ** argc){
hw();
return 0;
}
// BUILD COMMAND (ommitting proj directories, replacing with '.')
g++ -I. -o hw.o hw.cpp
// Archive Command
ar -rcs hw.a hw.o
// Compile (works as expected)
g++ -I. -o hw main.cpp hw.a
// Compile with ld
g++ -I. -L. -o hw main.cpp -lhw
结果是失败了。我尝试过绝对路径,查看了 ld 文档;总的来说,花时间试图弄清楚这个问题。
这里可能发生了什么?
确切的错误代码:
/usr/bin/ld: cannot find -lhw
collect2: error: ld returned 1 exit status
我猜你的错误消息,但在我自己尝试你的代码后,我认为你的问题是 ld 找不到你的库。库必须以前缀 lib
命名。将 hw.a
重命名为 libhw.a
,它应该可以工作。
我编译了一个 hello world 库来测试我的构建设置:
// hw.cpp
#include<iostream>
#include"hw.h"
void hw(){ std::cout << "hw"<<std::endl; }
// hw.h
void hw();
// main.cpp
#include"hw.h"
int main(int argv, char ** argc){
hw();
return 0;
}
// BUILD COMMAND (ommitting proj directories, replacing with '.')
g++ -I. -o hw.o hw.cpp
// Archive Command
ar -rcs hw.a hw.o
// Compile (works as expected)
g++ -I. -o hw main.cpp hw.a
// Compile with ld
g++ -I. -L. -o hw main.cpp -lhw
结果是失败了。我尝试过绝对路径,查看了 ld 文档;总的来说,花时间试图弄清楚这个问题。
这里可能发生了什么?
确切的错误代码:
/usr/bin/ld: cannot find -lhw
collect2: error: ld returned 1 exit status
我猜你的错误消息,但在我自己尝试你的代码后,我认为你的问题是 ld 找不到你的库。库必须以前缀 lib
命名。将 hw.a
重命名为 libhw.a
,它应该可以工作。