Home > OS >  How to add glib header file in C?
How to add glib header file in C?

Time:12-22

I am getting a compilation error saying:

In file included from glib.c:5:
/usr/include/glib-2.0/glib.h:30:10: fatal error: glib/galloca.h: No such file or directory
   30 | #include <glib/galloca.h>
      |          ^~~~~~~~~~~~~~~~
compilation terminated.

when I try including glib to my C program

#include <stdio.h>
#include <glib-2.0/glib.h>

int main () {
    printf("Hello World");
}

I am trying to include the glib header file to my C file but I keep getting complilation error.

I tried compiling with the following commands:

gcc glib.c

This gives me the above error

gcc `pkg-config --libs glib` glib.c

This gives me the below error

gcc: error: unrecognized command-line option ‘--libs’; did you mean ‘--libs=’?
gcc `pkg-config --libs=glib` glib.c

This also gives me an error,

cc1: warning: command-line option ‘-flibs=glib`’ is valid for Modula-2 but not for C
In file included from glib.c:5:
/usr/include/glib-2.0/glib.h:30:10: fatal error: glib/galloca.h: No such file or directory
   30 | #include <glib/galloca.h>
      |          ^~~~~~~~~~~~~~~~
compilation terminated.

I also tried using the full path

#include </usr/include/glib-2.0/glib.h>

yet it gives me the same compilation error

CodePudding user response:

If you run the command pkg-config --libs glib-2.0 on its own, you will see that it only lists the libraries to link with. It give you the linker flags, not the compiler flags needed to compile your program.

To get the compiler flags you need to use the --cflags option:

gcc `pkg-config --cflags glib-2.0` -Wall -Wextra glib.c -o glib `pkg-config --libs glib-2.0`

Note that I separate the compiler and linker flags. That's because libraries needs to be listed last on the command line.

Also note that I added some flags to enable more warnings, which is generally a good idea (and you should really treat and warning you get as an error that must be properly fixed).


It also seems to be an issue with using backtick commands, and the error is typical when using e.g. Fish instead of Bash.

There are two major issues working against you here:

To solve this we need to use e.g. this instead:

gcc \
  (pkg-config --cflags glib-2.0 | string split -n " ") \
  -Wall -Wextra glib.c -o glib \
  (pkg-config --libs glib-2.0 | string split -n " ")

It might be simpler to use a simple Makefile or other similar built-tools to help you.

  • Related