标题在 Visual Studio Code 中的 C++ 中似乎不起作用

问题描述 投票:0回答:2

我目前正在使用 Visual Studio Code 来学习 C++,使用《加速 C++》一书的第 4 章。它涉及一个包含多个函数的程序,只要所有内容都在一个 .cpp 文件中,它就可以正常工作。 将函数分成三个具有相应标头的 .cpp 文件(全部位于同一文件夹中)并尝试通过右上角的按钮“运行 c/c++ 文件”后,出现错误“'...\program.exe” '不存在”(可以选择打开'launch.json')并表示“对'...'的未定义引用。 未定义的引用错误始终是主程序必须使用的标头中的第一个函数。

我用简单的“Hello world!”尝试了同样的事情。如果所有内容都在一个 .cpp 文件中,它可以正常工作,但会给出相同的错误“运行 c/c++ 文件”。以下代码:

主程序(greet.cpp):

#include<iostream>
#include"hello.h"

using std::cout; using std::endl; using std::cin;

int main()
{
    cout << hello(cin) << endl;
return 0;
}

标头(hello.h):


#ifndef GUARD_hello_h
#define GUARD_hello_h

#include<string>
#include<iostream>

std::string hello(std::istream&);

#endif

hello 函数(hello.cpp):

#include"hello.h"
#include<iostream>
#include<string>

using std::istream; using std::string; using std::cout; using std::endl;

string hello(istream& in)
{
    cout << endl << "Please enter your name:   ";
    string name;
    in >> name;
    cout << endl;
    string hi = "Hello " + name + "!";
    return hi;
}

“世界你好!”使用 cmd 终端并输入 g++ -ogreet.exegreet.cpp hello.cpp 时确实有效,这对我的主要问题不起作用,而且似乎也不应该是解决方案。

c++ visual-studio-code header
2个回答
0
投票

正如多条评论中所指出的,答案是将tasks.json 文件中的

${file}
替换为
"${workspaceFolder}/*.cpp"
来编译所有.cpp 文件,而不仅仅是活动文件。谢谢您的帮助!


0
投票

对我来说,问题是 c_cpp_properties.json 中的 intelliSenseMode。将其更改为“linux-clang-x64”

© www.soinside.com 2019 - 2024. All rights reserved.