编译C代码遇get_string未定义引用及cs50.h缺失问题求助
解决C语言编译中的CS50库相关错误
一、cs50.h: No such file or directory 错误解决
编译器找不到cs50.h是因为CS50不属于C标准库,需要手动配置头文件路径:
- 若已下载CS50库文件,编译时用
-I参数指定头文件所在目录。比如cs50.h存放在C:\cs50\include下,编译命令为:cc -I C:\cs50\include test.c -o test - 若使用
make test命令,需创建或修改Makefile,添加头文件与库文件路径配置。示例Makefile内容:test: test.c cc -I C:\cs50\include test.c -L C:\cs50\lib -lcs50 -o test - Windows用户也可直接安装CS50官方开发环境,或通过WSL(Windows子系统Linux)执行
sudo apt install libcs50-dev安装库包,系统会自动识别头文件路径。
二、undefined reference to 'get_string' 链接错误解决
该错误是因为链接阶段找不到get_string的实现代码——CS50的函数封装在独立库文件中,必须显式链接:
- 编译时用
-L指定库文件目录,-lcs50链接CS50库。比如库文件在C:\cs50\lib下,命令为:cc test.c -I C:\cs50\include -L C:\cs50\lib -lcs50 -o test - 若使用WSL/Linux环境,安装
libcs50-dev后,直接用以下命令即可完成编译链接:cc test.c -lcs50 -o test
代码语法修正
你的代码存在两处小问题,修正后可避免潜在编译警告:
#include <stdio.h> #include <cs50.h> int main(void) { string name = get_string("what is your name?: "); printf("hello world, %s\n", name); }
- 补全
get_string语句末尾的分号 - 调整
printf缩进,并在输出字符串中添加逗号与换行,提升可读性
内容的提问来源于stack exchange,提问作者ayham
相关产品推荐
相关产品推荐

