how gcc automatically know to include glib library

2019-03-01 11:04发布

问题:

I make simple program in C which uses glib.h, but when I compile it I get an error like:

$ gcc test.c -o test
test.c:3:18: fatal error: glib.h: No such file or directory
compilation terminated.

So from above it seems gcc can't find glib.h file (which is a part of the libglib2.0-dev package and have already installed it). So first I try locate glib.h files in my system and found output as below:

$ locate glib.h
/usr/src/linux-headers-3.2.0-29-generic-pae/include/config/blk/dev/bsglib.h
/usr/src/linux-headers-3.2.0-48-generic-pae/include/config/blk/dev/bsglib.h
/usr/src/linux-headers-3.2.0-57-generic-pae/include/config/blk/dev/bsglib.h

then I have tried command:

$ pkg-config --cflags glib-2.0
-I/usr/include/glib-2.0 -I/usr/lib/i386-linux-gnu/glib-2.0/include  

to get the right flags for GCC but still it show same error.

So have try to find solution from SO and found exact solution like

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

this command solve my problem

But I have question that, is not any way to tell gcc include glib library so not require to give flag pkg-config --cflags --libs glib-2.0 after gcc and simply I compile my file by gcc test.c -o test?

回答1:

No.

The problem of looking at C source code and figuring out which libraries it uses is very hard. It feels kind of "AI complete" to me, which is why it's typically solved manually by the programmer pointing out the exact right libraries to satisfy the dependencies with.

Just for glib, it's easy to imagine a system with both glib 1.x and 2.x versions installed, and some calls are named exactly the same. Now try to imagine a computer program capable of decucing what you meant, which library to link with. It's not possible, since only the programmer knows.

The pkg-config tool helps with the mechanics of what each library requires in order to be used, but it's still up to yuo to tell it (via the module name argument(s)) which exact libraries to use.