Skip to end of metadata
Go to start of metadata

Creating Shared and Static library with gcc

How to handle Segmentation faults

  • Be sure that segfaults create core dumps. At your shell (bash) prompt, type: ulimit -c unlimited
  • Run: gdb /location/of/core/file/c-c++ executable /location/of/core/file
  • once within gdb type run
  • command bt will get a full backtrace



  • Compile and link your code: g++ -pg test1.cpp -o test1



  • Make sure to compile and link your code with options '-pg'
  • Run your executable. With flag '-pg' turned ON, this should output a gmon.out file.
  • To run gprof: gprof --no-graph test1 gmon.out > gprof.log



Shared objects are not profiled by gprof. sprof is the tool used to profile such shared libraries. It can be used only on one shared object at a time. Only functions in the shared library will be profiled. Profiling will be done irrespective of the application/code that uses this library. For eg. the shared library might be called from R, MatLab or other C code. But the library will be profiled as long as the calling application follows some protocol during invocation (Ref 2: Section 2.7, pg 33).

Generating Profile Data

  • Check if sprof is installed on your system: which sprof
  • To generate profiling data, two environment variables (LD_PROFILE, LD_PROFILE_OUTPUT) have to be set first
  • Specify the library to be profiled with absolute path: export LD_PROFILE=/path/to/shared/library/
  • Specify where you want the profile data file stored: export LD_PROFILE_OUTPUT=/path/to/identical/directory/tree.
  • Run your application.
  • A profile data file ( will be generated. This file will be placed at path/in/LD_PROFILE_OUTPUT/path/in/LD_PROFILE.

Running sprof

  • Once the .profile file is generated, run sprof to get the summary and redirect the output as desired
  • sprof -p -q > outputFile.txt
  • This will produce a summary of the execution profiling


  • The second path will be prefixed to the first path to identify the output directory.
  • Hence LD_PROFILE_OUTPUT should have a path to a directory which contains a directory tree identical to the one where the shared library exists.
  • For e.g. if LD_PROFILE = /usr/local/libs/ and LD_PROFILE_OUTPUT=/home/foo, then the profile data will be written to /home/foo/usr/local/libs/ if such a place exists.
  • If such a folder does not exist, no error is generated and no file is written (sad)
  • Here's a tip: If you have write access to the folder that contains the shared object then declare LD_OUTPUT_PROFILE=/ (i.e root). This will write the .profile file to the same directory as the shared object.



Profile C/C++ code from R


This content should probably be reorganized by someone who is doing more active C/C++ development. I'm putting it here for lack of a more general C/C++ development page.

nm -D (lists symbols from object files)
gcc -fpermissive
CXXFLAGS=-fpermissive ./configure

  • None