Compiling, Linking and Debugging Tips for C++

来源:互联网 发布:精美图表制作软件 编辑:程序博客网 时间:2024/05/19 23:58

Copy from http://www.cs.swarthmore.edu/~newhall/unixhelp/debuggingtips_C++.html


INDEX

Compiling C++ programsg++, make
Interpreting linker errorsc++filt, nm, dump, objdump, ldd
Debugging C++ programsgdb and valgrind


COMPILING

On the Linux machines use GNU's C++ compiler, g++,to compile your C++ code.Compile your code with warnings turned on (-Wall turns onall warnings). And don't ignore warnings as you compile your code; warningsusually indicate a lurking problem that can lead to real problems later.Also, always create a Makefile and use make to build your project code.Here is some more information aboutmake.

For more information about g++ and make see theGNU manuals or runinfo (the man pages for g++ and make are not very complete).


LINKING

A common link-time error is forgetting to link library code into yourprogram that uses it. If the compiler fails at link time with a list of undefined symbols in your program, it is due to your not linking in one or more .o files or library .a or .so files into your program (if you get an undefined reference error when a fileis being compiled from .C to .o, then this means you forgot to includea header file). For example, if you are calling thesqrt function from the math library, you need to include the math.h header file in your .C fileand you need to explicitly link the math library into your executable:

g++ -g -Wall -o myprog myprog.o -lm^^^
For C and C++ library functions, look at the man page for informationon how to link in the library code as part of the g++ command line.For other library code, including libraries you have written, you need totell the linker where the library code is located. To do this use the-L command line option followed by the path(s) to librarycode. For example, if I have two libraries in/home/newhall/mylibs/, one of which is a shared object file namedlibmymath.so and the other an archive file named libsimple.a,then I'd add the following to my makefile to link in these two libraries plus the standard math library (this is only part of the makefile):
# add the path to my library code; -L tells the linker where to find itLFLAGS += -L /home/newhall/mylibs# list of libraries to link into executable; -l tells the linker which # library to link into the executable LIBS = -lmymath -lsimple -lmOBJS = myprog.o# path to any header files not in /usr/include or the current directory INCLUDES += -I/home/newhall/include -I../includedefault: myprogmyprog:        $(CC) $(CFLAGS) $(LFLAGS) -o myprog $(OBJS) $(LIBS)${OBJS}: %.o :  %.c        ${CC} -c ${CFLAGS} ${LFLAGS} ${INCLUDES} ${@:.o=.c}
Deciphering linker errors containing mangled names

Because C++ compilers mangle names, often times one cannot easilydecipher linker errors. For example, by looking at the following output from the linker:

Undefined                       first referenced symbol                             in filefoo__FifP12BufHashTable             buf.old: fatal: Symbol referencing errors. No output written to buftestmake: *** [buftest] Error 1
it may not be obvious what the symbol foo__FifP12BufHashTable is because it is mangled. To get a mangled name's demangled form you can usec++filt:
% c++filt foo__FifP12BufHashTablefoo(int, float, BufHashTable *)# the symbol's demangled form
Symbol Tables and Library Dependencies

To list symbols in .so .a .o or an executable files, you can use nm orobjdump -t to list the contents of the symbol table. The output will include all symbols (e.g. functions,global variables), and will list information about them including if theyare defined or not (defined in a .o means the code for this function orthe declaration of this global variable is in this file, undefined meansit is in some other .o, .a, or .so file).

Executable files that are built using static linking contain all the library code needed to run. Executable files that are built using dynamic linking do not contain library code from .so files. Instead, library code from .so files is dynamically loaded into the address space of the process at runtime. To list the shared object dependencies of an executable file (or of a .so file) useldd.ldd will list the name of each shared object file and the full path toits location. If a program fails at runtime with a linking error, it isdue to the runtime linker not being able to find one or more of the .so files needed to run the executable.

% ldd a.out linux-gate.so.1 =>  (0xffffe000) libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb7e53000) libm.so.6 => /lib/tls/libm.so.6 (0xb7e1c000) libgcc_s.so.1 => /lib/libgcc_s.so.1 (0xb7e11000) libc.so.6 => /lib/tls/libc.so.6 (0xb7cdf000) /lib/ld-linux.so.2 (0xb7f3b000)
Runtime errors

If you get runtime errors like the following:

$ ./a.outa.out: error while loading shared libraries: libmylib.so: cannot open shared object file: No such file or directory
this means that the runtime linker cannot find a .so file (libmylib.so inthis example). This most often occurs when you link in shared object filesthat are not in /usr/lib, but can also occur when the a.out file was builtusing libraries in /usr/lib that are no longer present when you try to runit (often times this can be fixed by re-compiling, but may require re-installingthe missing libraries). To fix the problem when the shared object file isa directory different from /usr/lib, you need to set your LD_LIBRARY_PATHenvironment variable to include a path to .so files need at runtime.For example, if I put my .so files in a directory named lib in my homedirectory, I'd set my LD_LIBRARY_PATH enviroment to the following:
  # if running bash:  export LD_LIBRARY_PATH=/home/newhall/lib:$LD_LIBRARY_PATH  # if running tcsh:  setenv LD_LIBRARY_PATH /home/newhall/lib:$LD_LIBRARY_PATH
See Building and Linking Libraries in C (or C++) for more information on building and using your own library code.

DEBUGGING: gdb, ddd, valgrind

gdb and ddd

Debugging tools allow you to see what is going on inside your programas it runs and/or let you see what your program was doing when itcrashed. gdb and ddd allow you to examine a program'sstate (variables, stack frame contents, etc.), allow you to set breakpointsto stop the program at a certain points to examine its state, and allowyou to alter the value of your program's state (change a variable'svalue, call a function) as it runs. Learning to use a debugger can save youhours/days of time over trying to debug via printf statements.

GDB Guide:
"how to use gdb" information, including information on compiling C++ programs for use with gdb, running gdb, commonly used commands, example sessions,gdb and make, ddd, and keyboard shortcuts.

Some sample programs that you can copy and try out with gdb are available here:/home/newhall/public/gdb_examples/

Setting breakpoints in C++ code: One complication with gdb and C++ programs, is that you need to specify methods and data members using the "classname::" prefix. In addition, you often need to use a leading ' before the name for gdb to find the symbol, and if methods are overloaded, you need to specify which method it is by listing its full prototype (actually, if you hitTAB gdb will list all possible matches for you and you can pick one of those).

For example, to set a break point in funciton pinPage of the BufMgr class,I'd do the following:

(gdb) break 'BufMgr::pinPage(int, Page *&, int)'
Actually, I'd just type break 'BufMgr::p then hit TAB for automatic completion.
(gdb) break 'BufMgr:: <tab> will list all methods of the BufMgr class

valgrind

valgrind is a tool for finding memory access errors in your code (memory leaks, reading uninitialized memory, accessing unallocated memory, array out-of-bounds errors, ...). In C and C++ programs, memoryaccess errors are the most difficult bugs to find and to fix. valgrind can save you days worth of debugging effort by quickly pointing you to the source and type of these memory access bugs in your program code.valgrind is pretty easy to learn to use, and the effort you put in to learnhow to use it will be more than made up for by the debugging time you save by using it.

Some sample programs that you can copy and try out with valgrind are available here:/home/newhall/public/purify_valgrind_examples/

valgrind Guide: "using valgrind" information with a sample valgrind session and links to valgrind references.

 

原创粉丝点击