C++ compiles but gives error when executed

偶尔善良 提交于 2019-12-22 08:28:25

问题


I am new to Linux Ubuntu 11.10 and have basic C++exposure.

I installed the g++ by

sudo apt-get install build-essential

and created a directory cpp in my home directory. I then wrote a program hello.cpp in my cpp directory

#include <iostream>
using namespace std;

int main() {
    cout << "Hello !" ; return 0;
}

and compiled using

g++ -W hello.cpp -o hello

The program compiles without any errors/warnings. When I try to execute the file

./hello.cpp

I get error messages:

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

I tried looking at a lot of posts but could not resolve this. I have MS VisualStudio on Windows, but I would rather learn C++ on Ubuntu. Thanks in advance.


回答1:


I think that the problem is that you're trying to execute the .cpp source file rather than the generated executable. Try running ./hello instead of ./hello.cpp, since hello is the actual executable. The errors you're currently getting are caused by the shell interpreter choking on C++ syntax, since it's trying to run it as a shell script.

Hope this helps!



来源:https://stackoverflow.com/questions/9070110/c-compiles-but-gives-error-when-executed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!