Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 848
sunny Avatar asked Jan 30 '12 20:01

sunny


1 Answers

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!

like image 78
templatetypedef Avatar answered Sep 22 '22 15:09

templatetypedef