使用 CodeRunner 扩展使用 VStudio Code 运行C++

Running C++ with VStudio Code using CodeRunner extension

本文关键字:Code 运行 C++ VStudio CodeRunner 扩展 使用      更新时间:2023-10-16

我无法使用代码运行器扩展从VStudio代码运行我的.cpp文件。

当我在 main 中用#include "test.cpp"替换#include "test.h"时,它工作正常,但将其替换回来会给我以下错误;

[Running] cd "c:\Users\dree\Desktop\TestRun\" && g++ main.cpp -o main && "c:\Users\dres\Desktop\TestRun\"main c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:\Users\dree\AppData\Local\Temp\ccm2RSvw.o:main.cpp:(.text+0x15(: 对 'MyClass::foo((' collect2.exe: error: ld 返回 1 个退出状态

[完成] 在 1.1 秒内以 code=1 退出

主.cpp

#include "test.h"
#include <iostream>
int main()
{
MyClass a;
a.foo();
return 0;
}

测试.cpp

#include "test.h"
#include <iostream>
void MyClass::foo()
{
std::cout << "Hello World" << std:: endl;
}

测试.h

class MyClass
{
public:
void foo();
int bar;
};

设置.json

{
"workbench.colorTheme": "Visual Studio Dark",
"workbench.iconTheme": "material-icon-theme",
"python.linting.flake8Enabled": false,
"terminal.integrated.shell.windows": "C:\WINDOWS\System32\cmd.exe",
"editor.minimap.enabled": false,
"liveServer.settings.donotShowInfoMsg": true,
"python.pythonPath": "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\python.exe",
"python.linting.pylintEnabled": true,
"python.linting.enabled": true,
"explorer.confirmDelete": false

}

有没有办法更改代码运行程序扩展以调用 g++ 命令,其中包含正在运行的文件目录中的所有.cpp文件?

例如: 它正在运行以下命令;

cd "c:UsersdreesDesktopTestRun" && g++ main.cpp -o main && "c:UsersdreesDesktopTestRun"main

我可以以某种方式将其更改为此内容吗?

cd "c:UsersdreesDesktopTestRun" && g++ *.cpp -o main && "c:UsersdreesDesktopTestRun"main

通过更改代码运行程序扩展的设置来解决;

将其添加到我的设置.json文件中;

"code-runner.executorMap": {
"cpp": "cd $dir && g++ *.cpp -o $fileNameWithoutExt && $fileNameWithoutExt.exe"
}

这就是我为C++设置代码运行程序的方式

code-runner.executorMap": {
"cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt && ./$fileNameWithoutExt && rm ./$fileNameWithoutExt",
}

此命令告诉代码运行程序

  1. 切换到我当前源代码所在的目录
  2. 编译代码
  3. 执行二进制文件
  4. 已删除二进制文件

正如 drescherjm 所指出的,问题出在传递给编译器的参数中:输出显示使用的命令是g++ main.cpp -o main。没有参考测试.cpp!

你可能认为告诉 g++ 编译 main.cpp 就足够了,因为它包含了 test.h,显然test.h 中任何内容的定义都可以在 test.cpp 中找到。不幸的是,这对您来说是显而易见的,但对编译器来说却不是。同名但扩展名不同的文件(如test.cpp和test.h(是相关的,这对我们程序员来说非常方便,但编译器不知道。它只知道test.h声明了一个名为MyClass的类,但它不知道它的定义在test.cpp内部。要解决它,你必须像这样调用 g++:

g++ main.cpp test.cpp -o main

也就是说,您必须显式列出必须用于构建 main 的所有源文件。

这就是为什么用#include "test.cpp"替换#include "test.h"的原因:因为这样你告诉编译器获取测试的内容.cpp并将其粘贴到main.cpp的顶部,以便MyClass的定义可用。但这是一种代码气味:如果你包含一个.cpp文件,你可以非常确定你做错了什么。编译器不关心扩展名,.h 或 .cpp 对它是一样的,这就是它工作的原因。但你应该避免它。

只是想发布对我有帮助的东西。我尝试了 dree 的答案,但不断出现错误

编辑代码运行程序执行器映射设置,但请使用以下命令:

"cpp": "cd $dir && g++ -o $fileNameWithoutExt *.cpp && $dir$fileNameWithoutExt",