当我运行此hello world函数时:
#include <iostream>
/*
welcome to your first c++ tutorial! Congrats lets have some fun :)
*/
int main() {
std::cout << "hello world\n";
int e{ 2 };
std::cout << e;
return 0;
}
我收到此错误:
[Running] cd "/Users/tbarton/Documents/GitHub/c++ practice files/" && g++ main.cpp -o main && "/Users/tbarton/Documents/GitHub/c++ practice files/"main
main.cpp:9:10: error: expected ';' at end of declaration
int e{ 2 };
^
;
1 error generated.
[Done] exited with code=1 in 0.388 seconds
我是C ++的超级菜鸟,所以迷路了。知道是什么吗?
答案 0 :(得分:3)
也许您的编译器较旧,而不是为c ++ 11(或更高版本)设置的。您可以尝试:
g++ main.cpp -o main -std=c++11
在此处查看您的相同代码:https://godbolt.org/z/77oc5Y
这是运行-std = c ++ 98的相同代码:https://godbolt.org/z/aEszPb(出现错误)
更新
由于上述链接将来可能会停止工作,因此输出如下:
使用gcc 4.1.2编译:
<source>: In function 'int main()':
<source>:9: error: a function-definition is not allowed here before '{' token
<source>:10: error: 'e' was not declared in this scope
Compiler returned: 1
使用gcc 10.2编译:
ASM generation compiler returned: 0
Execution build compiler returned: 0
Program returned: 0
hello world
2
由gcc 10.2编译,带有编译器标志-std = c ++ 98:
<source>: In function 'int main()':
<source>:9:10: warning: extended initializer lists only available with '-std=c++11' or '-std=gnu++11'
9 | int e{ 2 };
| ^
ASM generation compiler returned: 0
<source>: In function 'int main()':
<source>:9:10: warning: extended initializer lists only available with '-std=c++11' or '-std=gnu++11'
9 | int e{ 2 };
| ^
Execution build compiler returned: 0
Program returned: 0
hello world
2