简体   繁体   中英

C++ compiles but gives error when executed

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM