Sunday, January 30, 2011

C++ Cookbook

I used the commands below to compile the first exercise in O'Reilly's C++ Cookbook. The book provides the commands to compile and link for several different compilers. I had difficulty finding the command to link to the dynamic library when creating the executable. To compile a module with dependencies on the newly created dynamic library, use the highlighted command below.

libjohnpaul.a is statically linked. libgeorgeringo.dylib is dynamically linked. In order for hellobeatles to run, libgeorgeringo.dylib must be copied into the same folder as the hellobeatles executable.
[greg:johnpaul] g++ -c -o john.o john.cpp
[greg:johnpaul] g++ -c -o paul.o paul.cpp
[greg:johnpaul] g++ -c -o johnpaul.o johnpaul.cpp
[greg:johnpaul] ar ru libjohnpaul.a john.o paul.o johnpaul.o
[greg:johnpaul] ranlib libjohnpaul.a
[greg:johnpaul] cd ../georgeringo
[greg:georgeringo] g++ -c -o george.o george.cpp
[greg:georgeringo] g++ -c -o ringo.o ringo.cpp
[greg:georgeringo] g++ -c -o georgeringo.o georgeringo.cpp
[greg:georgeringo] g++ -dynamiclib -fPIC -o libgeorgeringo.dylib george.o ringo.o georgeringo.o
[greg:georgeringo] cd ../hellobeatles
[greg:hellobeatles] g++ -c -I.. -o hellobeatles.o hellobeatles.cpp
[greg:hellobeatles] g++ -o hellobeatles hellobeatles.o -L../johnpaul -L../georgeringo -ljohnpaul -lgeorgeringo
[greg:hellobeatles] cp ../georgeringo/libgeorgeringo.dylib libgeorgeringo.dylib
[greg:hellobeatles] ./hellobeatles
John, Paul, George, and Ringo
[greg:hellobeatles] 
The book, including the source for each Beatle, can be found online. The online version has some significant differences with the PDF available from O'Reilly.