Tuesday, March 5, 2013

g++ compiler options

Four stages of creating a program
  1. Preprocess
  2. Compile
  3. Assemble
  4. Link
Example: Creating and using a shared library (lib*.so - filename starts with prefix "lib" and ends with suffix ".so"):
First, we'll create the object file from the source.
g++ -c <filename.cpp> -o <filename.o>
-c specifies that we're only compiling, not linking. We do this when filename.cpp doesn't have a main function so there's nothing to link.
-o specifies the output file name. Note that it doesn't have to end in .o, but the .o ending is convention for object file
Next, we'll create the shared object file library from the object file
g++ -shared -fPIC <filename.o> -o <libfilename.so>
-shared indicates that we're creating a shared library
-fPIC indicates that we're creating position independent code.
Excellent, we've now created a shared library!

Now for the fun part, linking, the biggest headache of them all. Let's say we wan't to use the library in <appname.cpp>.
g++ <appname.cpp> -L. -l<filename> -Wl,-rpath,. -o <appname>
-L. tells the g++ to look in the current directory (hence the ".") at link-time for the library.
-l<filename> tells which library we'll be using (Although the library will look something like lib<filename>.so, the convntion is -l<filename>).
-Wl,<ld option> passes <option> to the linker. <option> can be comma separated for multiple options as we do. By passing "-rpath,." to the linker, we tell it to use the current directory "." at run-time linking. Note the separation of link-time and run-time paths when looking for libraries.

Putting it all together looks something like

g++ -c <filename.cpp> -o <filename.o>
g++ -shared -fPIC <filename.o> -o <libfilename.so>
g++ <appname.cpp> -L. -l<filename> -Wl,-rpath,. -o <appname>



No comments:

Post a Comment