【发布时间】:2020-10-10 17:28:12
【问题描述】:
我是 C++ 新手,正在学习我的第一个教程,当我尝试编译课程中的代码时,我收到以下错误:
expected ';' at end of declaration
int x{ }; // define variable x to hold user input (a...
^
;
我尝试运行的程序的完整代码:
#include <iostream> // for std::cout and std::cin
int main()
{
std::cout << "Enter a number: ";
int x{ };
std::cin >> x;
std::cout << "You entered " << x << '\n';
return 0;
}
我在 Macbook Pro 上使用 Visual Studio Code (v.1.46.1),带有 Microsoft C/C++ 扩展 (https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools)。
我的编译器是 Clang:
Apple clang version 11.0.3 (clang-1103.0.32.62)
Target: x86_64-apple-darwin19.5.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
最初,我在 VS Code 中运行 Terminal > Configure Default Build Task 来创建 .vscode/tasks.json 编译器设置文件。该文件当前如下所示:
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "C/C++: clang++ build active file",
"command": "/usr/bin/clang++",
"args": [
// Set C++ Standards
"-std=c++17",
// Increase compiler warnings to maximum
"-Wall",
"-Weffc++",
"-Wextra",
"-Wsign-conversion",
// Treat all warnings as errors
"-Werror",
// Disable compiler extensions
"-pedantic-errors",
// File to compile
"-g",
"${file}",
// Output file
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
我设置了-std=c++17 标志,据我所知,它应该允许直接大括号初始化。
我不确定这是否重要,因为我正在尝试编译而不是构建/调试,但为了彻底起见,我还有一个包含以下内容的 .vscode/launch.json 文件:
{
"version": "0.2.0",
"configurations": [
{
"name": "clang++ - Build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"args": [],
"stopAtEntry": true,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "lldb",
"preLaunchTask": "C/C++: clang++ build active file"
}
]
}
谁能帮我弄清楚为什么int x{ }; 无法正常初始化变量以及我可以做些什么来修复它以使其正常工作?
[编辑]:我检查/测试的其他设置:
- 使用
clang++ -std=c++17 -g helloworld.cpp -o helloworld直接从命令行运行编译时代码编译正确 - VS Code C/C++ 扩展配置已将“C++ 标准”设置为 c++17(似乎是默认设置)。即便如此,在没有设置
-std=c++17标志的情况下运行命令行编译也会导致相同的编译器错误。 - 尝试将
int x{ };更改为以下内容:-
int x( );: 失败并出现很长的错误列表 -
int x(0);:编译成功 -
int x = { };:编译成功 -
int x = {0};:编译成功 - `int x;':编译成功
- `int x = 0;':编译成功
-
【问题讨论】:
-
能不能在命令行编译,还是会报错?
-
源文件的名称是什么,包括扩展名? clang 从文件名中推断出语言,它可能认为这不是 C++。另外,除了显示的错误之外,还有其他错误吗?
-
@ChrisMM 是的,它确实使用 ``` clang++ -std=c++17 -Wall -Weffc++ -Wextra -Wsign-conversion -Werror -pedantic-errors -g helloworld 从命令行编译。 cpp -o helloworld ``` 当我删除命令行上的所有可选标志时,它也编译得很好,如下所示: ``` clang++ -std=c++17 -g helloworld.cpp -o helloworld ```
-
@NateEldredge 源文件称为
helloworld.cpp。这是我得到的唯一错误。完整的控制台输出是:``` 执行任务:/usr/bin/clang++ -g /Users/{redacted}/Documents/development/c++/learncpp/helloworld/helloworld.cpp -o /Users/{redacted}/Documents/ development/c++/learncpp/helloworld/helloworld -
-std=c++17显然没有被传递,并且您的编译器已经足够老,可以默认为 C++03,而该语法不起作用。
标签: c++ visual-studio-code compiler-errors c++17