practicalities

compiling and linking

In C the process of building a running program involves two steps: compiling code files proceeds independently for each file, to produce object files (ending with .o). These object files are then linked together with libraries to produce an executable (or another library).

When compiling, the header files, which describe the type of symbols, are important, When linking, it is library files that must be found and collected.

With experience, finding the appropriate header files for a given library is pretty easy. However, finding the right library files, and linking them in the right order, can be a challenge.

A program must have a single entry point, which in C is the main function. It must have exactly the form

int main( int c, const char *arg[] )

In a command-line environment, the array arg are the string arguments passed to the program, and c is the number of arguments. The return value is the exit status of the command, with 0 conventionally indicating a successful exit.

special C problems

stack corruption — usually occurs when the programmer lies to the compiler about the size of a variable passed as an argument.

segmentation fault — attempt to access unallocated memory, usually failing to set a pointer to null after deleting it, and then attempting to access that, or failing to initialize a pointer to null and then attempting to access that memory.

memory leak — allocate memory without deleting it.

uninitialized variables — contain trash by default

comma after loop:

	for( i=0; i<n; i++ );
	{ /* block executed only once, with i=n */ }

compiler options

object files -o option
compile without linking -c option
include file path -I

linker options

libraries -l, path -L
static vs. shared libraries, and LD_LIBRARY_PATH

library tools

nm to look into static libraries

ldd look at dependencies

debugging

-g option for debug symbols
gdb the GNU debugger
valgrind finds run-time problems e.g. memory corruption and leaks.
gcov a coverage tool

profiling

-pg option (compile and link)
gprof