8

On AWS Ubuntu Server, I wrote C++ Hello, World program:

#include <iostream>
using namespace std;

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

And compiled it:

ubuntu@ip-xxxxx:~/dev/c++$ g++ -c ./test.cc -o out
ubuntu@ip-xxxxx:~/dev/c++$ chmod a+x out
ubuntu@ip-xxxxx:~/dev/c++$ ./out
-bash: ./out: cannot execute binary file: Exec format error
ubuntu@ip-xxxxx:~/dev/c++$ file ./out
./out: ELF 64-bit LSB  relocatable, x86-64, version 1 (SYSV), not stripped
ubuntu@ip-xxxxx:~/dev/c++$ uname -a
Linux ip-xxxxx 3.13.0-48-generic #80-Ubuntu SMP Thu Mar 12 11:16:15 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
ubuntu@ip-xxxxx:~/dev/c++$ gcc --version
gcc (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4

It seems that architecture x86-64 is the same each other. What is the problem here? Do I have to add more C++ flags?

3
  • Please edit your question and show us the contents of test.cc.
    – terdon
    Nov 11, 2015 at 16:46
  • @terdon I added my code.
    – Daebarkee
    Nov 11, 2015 at 19:53
  • @terdon the content of test.cc is irrelevant. Run touch test2.cc ; g++ -c test2.cc -o out ; chmod a+x out ; ./out. Same thing. Nov 11, 2015 at 20:15

1 Answer 1

20

The -c flag tells g++ to compile your source code to object code, but stop short of linking it with the necessary libraries to create a standalone executable binary. From man gcc:

   -c  Compile or assemble the source files, but do not link.  The linking
       stage simply is not done.  The ultimate output is in the form of an
       object file for each source file.

To create an executable program, simple run your command again without the -c flag:

g++ test.cc -o out

followed by

./out

(the executable flag will be set by default - an explicit chmod should not be required).

1
  • Yes. it works without -c. Thank you.
    – Daebarkee
    Nov 11, 2015 at 20:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.