Compiling C++ code on the command line

Brian —  March 20, 2012 — Leave a comment

Quick instructions for compiling small C++ projects on the command line in bash.

My normal development environment is to edit in Vim, and compile in a Visual Studio project.

However, I occasionally have an idea that I’d like to test out by itself, isolated from the rest of the code.
My usual solution is to write a small test program and compile it on the command line, debugging with writes to the output stream.

As an example, I recently wanted to refresh my memory about how string::find works.
I saw an example program at cplusplus.com

So to start, I just grabbed the example and saved it to string_find.cpp.

Now to compile it.
Hmmm.
First attempt:

[bash]
gcc -o string_find string_find.cpp
… massive list of errors omitted …
[/bash]

Well, that wasn’t it.

Look it up somewhere, can’t remember where, probably on stackoverflow.

Here’s what I want:

[bash]
g++ -Wall -o string_find string_find.cpp
> ./string_find.exe
first ‘needle’ found at: 14
second ‘needle’ found at: 44
‘haystack’ also found at: 30
Period found at: 51
There are two prepositions in this haystack with needles.
[/bash]

Awesome.
Now, post this to the blog so I don’t have to look it up again.
Whew!

Turns out that the gcc command will try to compile c++ code, but doesn’t link the standard library.
However, g++ does include the standard library, so stuff like are available.

No Comments

Be the first to start the conversation.

Leave a Reply

*

Text formatting is available via select HTML. <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>