【发布时间】:2021-10-05 01:02:36
【问题描述】:
我正在学习 C++,介绍 CS 类,我们现在开始为 OOP 实现数据抽象。我需要将类定义隐藏在单独的 .cpp 文件中并使用头文件。到目前为止,我一直在我的 Macbook pro 中使用 VSCode 中的默认设置来创建单个文件程序,所以我决定创建一个测试程序以确保在创建整个项目之前编译、包含和链接能够正常工作,但是现在当我尝试构建程序时,我收到一个错误。我已经尝试了几天使用潜在的解决方案来解决问题,但没有成功。我希望这里有人能带领我走向正确的方向。
我已经包含了 3 个测试文件(test.cpp、test.h 和 testImp.cpp)、c_cpp_properties.json、launch.json、settings.json 和 task.json 文件的内容以及错误的内容消息。
任何帮助设置 VSCode 以完成包括头文件将不胜感激,因为我将有更多具有此要求的项目。
谢谢你,詹姆斯。
test.cpp
#include <iostream>
#include "test.h"
using namespace std;
int main()
{
cout << testCalculation(5, 7) << endl;
cout << endl;
return 0;
}
测试.h
#ifndef test_h
#define test_h
int testCalculation(int, int);
#endif /* test_h */
testImp.cpp
#include "test.h"
int testCalculation(int x, int y) {
int sum = int();
sum = x + y;
return sum;
};
c_cpp_properties.json
"configurations": [
{
"name": "Mac",
"includePath": [
"${default}",
"${workspaceFolder}/**"
],
"compilerPath": "/usr/bin/g++",
"cStandard": "c17",
"cppStandard": "c++11",
"intelliSenseMode": "${default}"
}
],
"version": 4
}
launch.json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "g++ - Build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "lldb",
"preLaunchTask": "C/C++: g++ build active file"
}
]
}
setting.json
{
"files.associations": {
"iostream": "cpp"
}
}
task.json
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++ build active file",
"command": "/usr/bin/g++",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}
错误
Starting build...
/usr/bin/g++ -fdiagnostics-color=always -g /Users/jamesreal/cpp/cs-2/project-1/test.cpp -o /Users/jamesreal/cpp/cs-2/project-1/test
Undefined symbols for architecture x86_64:
"testCalculation(int, int)", referenced from:
_main in test-5cbf98.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
【问题讨论】:
-
您的错误在这里:
"${file}",这意味着您只想将活动文件构建到可执行文件中。该文档告诉您如何修复以在此处构建所有文件:https://code.visualstudio.com/docs/cpp/config-clang-mac#_modifying-tasksjson -
@drescherjm,我非常感谢你。我花了很多时间试图解决这个问题。我知道答案在某处的文档中,但我不知道去哪里找。我感激你。谢谢你,谢谢你,谢谢你。保持健康。
-
我花了一些时间才找到,但我相信上面的链接是合理的重复。
-
@drescherjm,是的,这有帮助。谢谢你。在那篇文章中有几个来源我也会审查,但你的第一个答案提供了一个解决方案。我感谢后续跟进并提供进一步的资源,这些资源可以更深入地了解问题。你摇滚!
标签: c++ json visual-studio-code g++ include-path