C++编译,但执行时出错

C++ compiles but gives error when executed

本文关键字:出错 执行 编译 C++      更新时间:2023-10-16

我是Linux Ubuntu 11.10的新手,有基本的C++公开。

我通过安装了g++

sudo apt-get install build-essential

并在我的主目录中创建了一个目录cpp。然后,我在我的cpp目录中编写了一个程序hello.cpp

#include <iostream>
using namespace std;
int main() {
    cout << "Hello !" ; return 0;
}

并使用进行编译

g++ -W hello.cpp -o hello

程序编译时没有任何错误/警告。当我尝试执行文件时

./hello.cpp

我收到错误消息:

line 3: using: command not found
line 6: syntax error near unexpected token `('
line 6: `int main() {'

我试着看了很多帖子,但没能解决这个问题。我在Windows上有VisualStudio,但我更愿意在Ubuntu上学习C++。提前谢谢。

我认为问题在于您试图执行.cpp源文件,而不是生成的可执行文件。请尝试运行./hello而不是./hello.cpp,因为hello是实际的可执行文件。您当前遇到的错误是由于shell解释器被C++语法阻塞导致的,因为它试图将其作为shell脚本运行。

希望这能有所帮助!