一、创建多个源文件程序
1.stuinfo.h
// stuinfo.h
#ifndef STUINFO_H
#define STUINFO_H
#include <string>
// 定义 student 结构体
struct student {
std::string name;
int age;
int score;
};
// 初始化学生信息的函数声明
void initStudent(student& stu);
// 打印学生信息的函数声明
void printStudent(const student& stu);
#endif
2.stuinfo.cpp
// stuinfo.cpp
#include "stuinfo.h"
#include <iostream>
// 初始化学生信息的函数定义
void initStudent(student& stu) {
// 在这里初始化 stu
stu.name = "Tom";
stu.age = 18;
stu.score = 90;
}
// 打印学生信息的函数定义
void printStudent(const student& stu) {
std::cout << "name:" << stu.name << std::endl;
std::cout << "age:" << stu.age << std::endl;
std::cout << "score:" << stu.score << std::endl;
}
3.main.cpp
// main.cpp
#include "stuinfo.h"
int main() {
// 声明并初始化 stu1
student stu1;
initStudent(stu1);
// 调用 printStudent() 函数打印 stu1 的信息
printStudent(stu1);
return 0;
}
二、错误分析
正在启动生成...
D:\vscode\mingw64\bin\g++.exe -fdiagnostics-color=always -g F:\Desktop\CODE\separate\main.cpp -o F:\Desktop\CODE\separate\main.exe
D:/vscode/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/13.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\pc\AppData\Local\Temp\cclYZgRg.o: in function `main':
F:\Desktop\CODE\separate/main.cpp:8: undefined reference to `initStudent(student&)'
D:/vscode/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/13.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: F:\Desktop\CODE\separate/main.cpp:11: undefined reference to `printStudent(student const&)'
collect2.exe: error: ld returned 1 exit status
生成已完成,但出现错误。
* 终端进程启动失败(退出代码: -1)。
* 终端将被任务重用,按任意键关闭。
原因分析:vscode使用g++编译的时候默认只编译了单个文件main.cpp,所以没有将stuinfo.cpp进行编译,导致程序在链接的过程中找不到printStudent(student const&)函数的符号。
三、解决办法
打开tasks.json
将"${file}"修改为"${fileDirname}\\*.cpp",如图所示:
tasks.json完整代码:
{
"version": "2.0.0",
"tasks": [
{
"label": "g++",
"command": "g++",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}.exe"
],
"problemMatcher": {
"owner": "cpp",
"fileLocation": [
"relative",
"${workspaceRoot}"
],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
},
"group": "build"
},
{
"type": "cppbuild",
"label": "C/C++: g++.exe 生成活动文件",
"command": "D:\\vscode\\mingw64\\bin\\g++.exe",
"args": [
"-fdiagnostics-color=always",
"-g",
"${fileDirname}\\*.cpp",
//"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "调试器生成的任务。"
}
]
}