Google Plus

run a C++ program from terminal

Written by Mel Kham on . Posted in Linux tutorials

 

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

Mel Kham

Founder of Unixmen, Living in Amsterdam. Am working in my free time to help people to understand the Opensource and to explain them in easy way how to make the fist steps to the the light. Working day and night with my Co-founder Zinovsky to keep this website live even with less resources.

Like us on Facebook

This week Top Posts

Write for us

Recent Comments

Ambiton

|

Thank you very much Chris :)

Lolman

|

in cmd

Oliver

|

Do you think that it works on a Macbook Air 1,1?… ohh and, it must be installed in a different partition than Mac OS X, right?… can´t have i installed only Ubuntu on my hard drive?

Nova

|

I wonder if there is a way to create your own themes.

 
IDG Tech Network
Copyright © 2008-2013 Unixmen.com .
Maintained by Anblik .