Search code examples
cgccpthreadsheader-filesgnome-terminal

How to compile a C program with a personal library that includes threads


I created a library for my C programs and this includes threads. I usually work with Code::Blocks and I never had problems, but now I need to compile programs directly from terminal. I saw that I need to write -lpthread but also my library name (its name is my_lib.h). I tried to compile first the library with gcc my_lib.c -c and this works; after, I tried this gcc main.c my_lib.h -o main -lpthread, but this doesn't work.

So what is the correctly sintax to compile this program that uses my_lib.h?


Solution

  • I assume my_lib.c is just a module (object file) rather than shared library.

    The compiling consists of two parts - compiling into object files and then linking:

    # compiling (note the -c)
    gcc -c my_lib.c
    gcc -c main.c
    # linking (no -c, just specify target with -o)
    gcc -o main main.o my_lib.o -lpthread
    

    Header files are never compiled (explicitly), they are just included from the .c files and therefore never produce .o file.