Turbo C++可运行代码在Dev C++中报clrscr未定义引用等错误求助
解决Dev C++中
undefined reference to 'clrscr'编译错误 这个问题很典型——你的代码依赖了Turbo C专属的非标准库函数,而Dev C使用的是标准GCC编译器,不支持这些函数。具体原因和修复方案如下:
问题根源
#include<conio.h>:这是Turbo C++特有的头文件,标准C和GCC编译器根本不认识它。里面的clrscr()(清屏)和getch()(等待按键输入)都是非标准函数,GCC找不到对应的实现,所以报链接错误。void main():标准C要求main函数必须返回int类型,void main是Turbo C的非标准写法,在GCC里可能会引发警告或错误。
修复步骤
1. 移除非标准头文件和函数
删掉#include<conio.h>,同时替换clrscr()和getch()为标准C支持的写法。
2. 替换清屏功能(可选)
如果需要保留清屏效果,标准C可以用system()函数调用系统命令:
- Windows系统:
system("cls") - Linux/macOS系统:
system("clear")
使用system()需要包含#include<stdlib.h>头文件。
3. 替换等待按键功能
getch()可以用标准的getchar()替代,但要注意scanf()读取输入后会在缓冲区留下换行符,直接用getchar()会读取这个换行符,导致程序直接退出。解决方法是先清空输入缓冲区:
// 在scanf之后添加这段代码,清除缓冲区剩余的换行符 while(getchar() != '\n');
4. 修正main函数的返回值
把void main()改成int main(),并在函数末尾添加return 0;,符合标准C规范。
修改后的完整代码(跨平台清屏版本)
#include<stdio.h> #include<stdlib.h> // 用于system()函数 int main() { int i; // 清屏:根据系统选择对应的命令 #ifdef _WIN32 system("cls"); #else system("clear"); #endif printf("Enter the number to be displayed: "); scanf("%d", &i); // 清除scanf留下的换行符 while(getchar() != '\n'); printf("The entered number is %d\n", i); printf("Press Enter to exit..."); getchar(); // 等待用户按回车 return 0; }
简化版本(不需要清屏)
如果不需要清屏功能,代码可以更简洁:
#include<stdio.h> int main() { int i; printf("Enter the number to be displayed: "); scanf("%d", &i); // 清除缓冲区换行符 while(getchar() != '\n'); printf("The entered number is %d\n", i); printf("Press Enter to exit..."); getchar(); return 0; }
验证
把修改后的代码复制到Dev C++中编译运行,就不会再出现undefined reference的错误了。
内容的提问来源于stack exchange,提问作者Mayank
相关产品推荐
相关产品推荐

