I compiled a list of notes while reading a book called “Advanced Linux Programming”. I already knew some of those, but rarely keep in mind while doing development. Others, I didn’t have any idea they existed! Here’s the list (still expanding in my laptop):
- You can #define variables in the command line while compiling through GCC. For example, to define NDEBUG while compiling a test.c file do:
gcc -o out -D NDEBUG test.c
gcc -o out -D NDEBUG=3 test.c
- Compile C programs with -O2 for production binaries.
- Learn to use GDB, especially for quickly finding Segmentation Faults.
- Use
getopt_long()
for command-line arguments parsing, instead of trying to parse them manually. Very handy! - stdout is buffered, stderr is not! Which means writing to stderr will immediately be flushed. Writing to stdout, however, will be buffered until later or until a call to
fflush(stdout)
. - Use
mkstemp()
andtmpfile()
for generating random file names for temporary files. - Using
abort()
will generate a core-dump. - If the library has both an archive (.ar) version and a shared object (.so) version, the program can be linked to the archive using -static. But by default, the shared object version is used.
- The libraries are searched in the current directory first by GCC during compilation.
- Using
ldd binary_name
will list all needed shared object it needs at runtime. It also lists indirect dependencies, i.e. libraries needed by the directly used libraries. - A binary can be forced to look for the shared object in a directory using
gcc -o app app.c -Wl,-rpath,/path/to/lib/directory
. DefiningLD_LIBRARY_PATH
environment variable is another solution. - Upgrading shared libraries doesn’t require the binaries to be recompiled/relinked etc.
- Static linking to libraries is good in scenarios where binaries will be installed in a non-privileged environment. So you don’t need
sudo make install
orsudo apt-get install something
. - Use
ps -o pid,ppid,command
to get process IDs, and the respective parent process IDs - Another useful output
ps
can give is the start time of the process. Useps -o start_time,command
to get the list.