login

C Basics

Some basic concepts about the programming language C

2023-09-19


Tips

Error Handling

Use a custom shared library

The shared library gets linked during runtime. A shared library should start with the prefix lib.

  1. Copy the header file to /usr/local/include/.
  2. Compile the shared library with cc -o libtest -shared -fPIC libtest.c.
  3. Copy the shared library to /usr/local/lib/.
  4. Add the folder to /etc/ld.so.conf if the entry doesn't already exist.
  5. Run ldconfig to load the library. Check with ldconfig -p | grep libterm if the library was loaded correctly.
  6. Include the library with #include <libtest.h>.
  7. Compile your application with cc -o main -ltest main.c. Run ldd main to see if the library is listed as dependency.

The following Makefile show how to create simple install/uninstall options:

Makefile

%gdefault:%n build

%gbuild:%n
  cc -o libtest -shared -fPIC libtest.c

%ginstall:%n build
  sudo cp libtest.h /usr/local/include/
  sudo cp libtest.so /usr/local/lib/
  sudo ldconfig
  rm libtest.so

%guninstall:%n
  sudo rm /usr/local/include/libtest.h
  sudo rm /usr/local/lib/libtest.so

%gclean:%n
  rm libtest.so

Libraries

Tools

Command Description
man <topic> View manual for a specific topic
xxd <file> View binary file as hex
ldd <file> View binary dependencies
file <file> View file type

Books