【C&C++】in function main‘: main.cpp:(.text+0x9): undefined reference to initscr‘
问题描述
/usr/bin/ld: /tmp/ccXkKcdN.o: warning: relocation against `stdscr' in read-only section `.text'
/usr/bin/ld: /tmp/ccXkKcdN.o: in function `main':
main.cpp:(.text+0x9): undefined reference to `initscr'
/usr/bin/ld: main.cpp:(.text+0x18): undefined reference to `move'
/usr/bin/ld: main.cpp:(.text+0x1f): undefined reference to `stdscr'
/usr/bin/ld: main.cpp:(.text+0x31): undefined reference to `wattr_on'
/usr/bin/ld: main.cpp:(.text+0x38): undefined reference to `stdscr'
/usr/bin/ld: main.cpp:(.text+0x4f): undefined reference to `waddnstr'
/usr/bin/ld: main.cpp:(.text+0x54): undefined reference to `refresh'
/usr/bin/ld: main.cpp:(.text+0x63): undefined reference to `endwin'
/usr/bin/ld: warning: creating DT_TEXTREL in a PIE
collect2: error: ld returned 1 exit status
原因分析
在链接阶段未能找到 ncurses 库中的函数定义。虽然在代码中包含了 curses.h
头文件,但在编译时没有链接 ncurses 库,因此链接器无法解析 initscr
、move
、stdscr
等函数的引用,从而导致错误。
解决方案
方法1
如果使用 g++,在编译参数中加入 -lncurses
以链接 ncurses 库:
g++ main.cpp -o main -lncurses
方法2
如果使用 Visual Studio Code,在 tasks.json
的 args
中加入 "-lncurses"
以链接 ncurses 库:
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++ build active file",
"command": "/usr/bin/g++",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}",
"-lncurses"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": "build",
"detail": "compiler: /usr/bin/g++"
}
]
}