run a C++ program from terminal

by
Share this Article: Facebook0Google+0Twitter0LinkedIn0Reddit0Pinterest0StumbleUpon0Digg

 

Linux doesn’t have extensions … it’s not a brain dead OS like Windows, at least not when it comes to actually developing anything.

To make life easy, however, there are certain conventions.

If I have a c++ source file called foo.cpp and I run

 

 

Code:
gcc -c -Wall -g foo.cpp

The program gcc will understand that foo.cpp is a C++ source file (not a fortran, C or java source file) and generate an object file with the extension .o

If I then do:

Code:
gcc -g -L/usr/lib -lstdc++ foo.o

gcc will understand that i intend to invoke the linker (ld) and use libstdc++.so in the /usr/lib directory, also — add debugging symbols.

Because I didn’t specify a target, gcc will produce a file a.out and set executable permissions on it.

I type:

Code:
./a.out

On the other hand I can specify a target with gcc:

Code:
gcc -g -L/usr/lib -lstdc++ foo.o -o foo.xxx.blah
./foo.xxx.blah

It makes no difference what I call the compiled binary executable, linux could care less.

Of course, for a simple program, I would skip the intermediate object:

Code:
gcc -g -Wall -lstdc++ foo.cpp -o foo

and now gcc understands that I want to compile a c++ source file, link it to the system’s standard c++ shared object and put the result (with debugging symbols) in a file called foo.

Or I can make my life even easier:

Code:
g++ -g -Wall foo.cpp -o foo

g++ is a program that does everything gcc did in the example above, but it only deals with c++ code and linkage.

 

Enjoy

For questions please refer to our Q/A forum at : http://ask.unixmen.com/

Share this Article: Facebook0Google+0Twitter0LinkedIn0Reddit0Pinterest0StumbleUpon0Digg