【发布时间】:2021-12-19 22:28:12
【问题描述】:
我正在尝试为一个简单的“hello world”之类的程序运行调试器,但遇到了链接错误。
我只有3个文件,Log.h、Log.cpp、Main.cpp:
Log.h
#pragma once
void InitLog();
void Log(const char *);
Log.cpp
#include "Log.h"
#include <iostream>
void InitLog()
{
Log("Initializing Log");
}
void Log(const char *message)
{
std::cout << message << std::endl;
}
Main.cpp
#include "Log.h"
// #include "Log.cpp"
int main()
{
int var = 9;
char x = 'a';
Log("hello world!");
}
我更改了我的代码运行程序设置,因为我收到了一个链接器错误,表明两个函数 Log() 和 InitLog() 已声明但未定义。
Undefined symbols for architecture x86_64:
"Log(char const*)", referenced from:
_main in main-f30cc3.o
"InitLog()", referenced from:
_main in main-f30cc3.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
切换代码运行器设置以编译目录中的每个文件:
"cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
"cpp": "cd $dir && g++ *.cpp -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
我提到这一点是因为我可能错误地连接了一些我不知道的东西(我什至应该需要更新代码运行器功能吗?)
虽然这适用于编译和链接代码,但由于同样的链接错误,我无法调试代码。我的CPP/.vscode/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"
}
]
}
我可以看到发生了相同的链接错误,并且使用 program 和 args 值对我不起作用。我的错误是:
终端错误:
> Executing task: C/C++: g++ build active file <
Cannot build and debug because the active file is not a C or C++ source file.
The terminal process failed to launch (exit code: -1).
Terminal will be reused by tasks, press any key to close it.
对此有一个简单的解决方案,我只需#include "Log.cpp"(我已评论的部分),调试器就可以工作了!
> Executing task: C/C++: g++ build active file <
Starting build...
/usr/bin/g++ -fdiagnostics-color=always -g CPP/07Debugging/Main.cpp -o CPP/07Debugging/Main
Build finished successfully.
Terminal will be reused by tasks, press any key to close it.
但是,我不想每次需要调试时都将.cpp 文件导入我的Main.cpp - 我在这里遗漏了什么吗?有没有办法以我不知道的方式编译和链接我当前目录中的所有 cpp 文件?搜索遇到相同调试器链接器错误的人已被证明是徒劳的,所以我认为我遗漏了一些明显的东西。我在 Mac 上运行 VSCode 并用 g++ 编译 c++
【问题讨论】:
标签: c++ c++11 visual-studio-code gcc vscode-debugger