VS Code远程SSH树莓派C编程:undefined reference问题求助
VS Code远程树莓派C开发本地头文件链接错误解决
问题说明
通过VS Code SSH远程连接树莓派开发C程序时,只要引入本地.h头文件,编译就会抛出undefined reference to '...'错误,但在终端手动编译并链接所有目标文件可正常运行。使用<>引入系统头文件无异常。
代码示例
- 无本地头文件可正常编译的代码:
#include <stdio.h> int main() { printf("Hello World\n"); }
- 本地头文件
Messages.h:
#ifndef MESSAGES_H_INCLUDED #define MESSAGES_H_INCLUDED void printMsg(char *str); #endif // MESSAGES_H_INCLUDED
- 头文件实现
Messages.c:
#include "Messages.h" void printMsg(char *str) { printf("Testausgabe: %s\n",str); }
- 修改后主程序:
#include <stdio.h> #include "Messages.h" int main() { printf("Hello World\n"); printMsg("Somthing else.\n"); }
编译报错信息
/usr/bin/ld: /tmp/ccBVuwoo.o: in function `main': helloworld.c:(.text+0x14): undefined reference to `printMsg' collect2: error: ld returned 1 exit status
终端手动编译成功命令
$ gcc -c helloworld.c $ gcc -c Messages.c $ gcc -o Hello helloworld.o Messages.o
VS Code自动生成的tasks.json
{ "tasks": [ { "type": "cppbuild", "label": "C/C++: gcc Aktive Datei kompilieren", "command": "/usr/bin/gcc", "args": [ "-fdiagnostics-color=always", "-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "Vom Debugger generierte Aufgabe." } ], "version": "2.0.0" }
解决方案(无需手动编写Makefile)
问题根源是VS Code默认的编译任务只编译当前激活的单个C文件,没有将同目录下的其他C实现文件(比如Messages.c)纳入编译链接流程。只需修改tasks.json的编译参数即可解决:
- 打开VS Code的
tasks.json:通过快捷键Ctrl+Shift+B,选择「配置默认生成任务」,然后选择对应的gcc任务进入编辑界面。 - 将
args数组中的"${file}"替换为"${fileDirname}/*.c",让gcc编译当前目录下所有C文件并自动完成链接。
修改后的tasks.json示例:
{ "tasks": [ { "type": "cppbuild", "label": "C/C++: gcc Aktive Datei kompilieren", "command": "/usr/bin/gcc", "args": [ "-fdiagnostics-color=always", "-g", "${fileDirname}/*.c", "-o", "${fileDirname}/${fileBasenameNoExtension}" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "Vom Debugger generierte Aufgabe." } ], "version": "2.0.0" }
修改完成后,再次按Ctrl+Shift+B执行编译任务,就能正常链接所有本地C文件,解决undefined reference错误。
内容的提问来源于stack exchange,提问作者schmokie
相关产品推荐
相关产品推荐

