C – 在Mac OSX Lion上编译时,架构x86_64的未定义符号
我在Mac OSX Lion上编译一个非常简单的name.c文件时遇到了一些问题。
现在,我开始在cs50.net上关注哈佛CS50课程。 我不是全新的编程,但我很好奇这门课程的教学方式。
这是name.c的来源:
#include #include int main(void) { printf("State your name:\n"); string name = GetString(); printf("O hai, %s!\n", name); return 0; }
如您所见,它需要这个库: https : //manual.cs50.net/CS50_Library 。
现在,当我编译它时,会发生这种情况:
Undefined symbols for architecture x86_64: "_GetString", referenced from: _main in name-vAxcar.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [name] Error 1
如果我在源文件中使用相同的GetString()cs50.c函数,它可以完美地工作:
#include #include #include #include #include #include typedef char *string; string GetString(void); int main(void) { printf("State your name:\n"); string name = GetString(); printf("O hai, %s!\n", name); } string GetString(void) { // CODE }
为什么会这样? 我在上面的链接上安装了库; 我检查过,cs50.h和libcs50.a分别位于/ usr / local / include和/ usr / local / lib中。
预先感谢您的帮助。
您遇到的问题是在链接阶段,而不是编译。 您没有提供GetString
的实现,只提供了它的声明(通过.h
文件#include
)。
要提供实现本身,通常需要链接包含它的库; 这通常由-l
标志到g++
。 例如,
g++ file.cpp -lcs50
您的第二个示例代码确实链接,因为您手动(并显式)为GetString
提供了一个实现,尽管是空的。