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?
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 chmod
ded 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With