Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running compiled program - "Invalid argument"

Tags:

c++

g++

I have simple Hello World C++ program (main.cpp):

#include <iostream>

using namespace std;

int main ( void ) {
    cout << "Hello world" << endl;
    return ( 0 );
}

I compile it through

g++ -Wall -pedantic -Wno-long-long -Werror -c main.cpp

then add the "be executable" permission

chmod +x main.o

and try to run it

./main.o

My console returns

-bash: ./main.o: Invalid argument

What am i doing wring?

like image 248
Radek Simko Avatar asked Feb 25 '23 20:02

Radek Simko


1 Answers

The -c option instructs the compiler to just compile the source file in an "object file", and not to link it.

Without the linking step the object file you get is not an executable, but just an intermediate step. What you probably want to do is

g++ -o main.x -Wall -pedantic -Wno-long-long -Werror main.cpp

This will generate the executable main.x (I usually use the .x for executables and .o for object files); notice that it will be already chmodded correctly for execution. (tip: another useful "lint-style" option is -Wextra; in optimized builds you should also consider -O3)

The intermediate step is often done when you have multiple files to compile and then link together; although you can simply pass all the sources as arguments to the compiler and let it do all the work, this means that at every recompilation you're recompiling all the source files, and if you start to have big projects this can be a problem in terms of wasted time (just to give you an idea: building OpenOffice.org from scratch can take more than 4 hours).

Instead, in these situations you just recompile the object files of the modified files, and link everything together passing the object files' names to g++ (or ld if you feel brave enough to fiddle with the linker options). In general this operation is automated with Makefiles or other build systems.

like image 74
Matteo Italia Avatar answered Mar 06 '23 23:03

Matteo Italia