Reputation: 5532
I am using GLFW libraries in my *.c program.
#include <GL/glfw.h>
#include <stdlib.h>
int main(void)
{
int running = GL_TRUE;
int k=0;
.....
...
..
The command I use to compile is:
gcc test1.c -o test1 -lglfw
My question is that, since this line is present:
#include <GL/glfw.h>
why do I have to pass -lglfw
to gcc
?
Upvotes: 2
Views: 238
Reputation:
GL/glfw.h is a header file, it declares all the types, constants, functions, you know the drill, it's to make the compiler know what code to generate and to make it not complain about unknown identifiers. libglfw is a library that contains the actual binary code (or stubs that will be bound later by the dynamic linker, or something like that), you have to link with it to make the linker not complain about unresolved symbols.
It's possible for the header to contain the actual source code of the library (so the compiler will generate the binary code over and over again for each translation unit where the library is used), it's called a header-only library then, but in the C world such libraries aren't something that you can find often and this particular library is not header-only.
Upvotes: 6
Reputation: 7164
Well, the header file (that with the .h) only contains declarations of say functions, variables classes and so on. So by including a header file in a .c file you make the declarations of the functions etc. known to the compiler. That means, the compiler is able to generate commands that actually call the functions.
However, the definition (i.e. the actual implementation) of a function is quite some different thing and it is (usually) not present in the header (which only contains declarations).
So in order to actually call into the implementation, the object code (i.e. the compiled source code) must also be present within the executable. This code, however, is contained in an external library (libglfw.a, in your case). So by adding the -lglfw option, you add the object code contained within the library to your executable which ensures that calls you make from your code will eventually find their way into the library code.
Bottom line: *.h file -> declaration only, no implementation
*.cpp, *.o, .a(.lib), .so(.dll, .dynlib) -> object code, implementation
Upvotes: 1
Reputation: 1
I don't know specifically the GLFW library. However, the #include
is a preprocessor directive for the compiler (if you miss it, your code won't compile), but the -lglfw
argument is for the linker (if you miss it, the code would be compiled to an object file, but you would get undefined symbols by the linker).
Some (rare) libraries are a header only things; they provide features entirely in the #include
-d headers. I only know one such library (GNU lightning).
Most libraries exist as shared or static library files (ie lib*.so
or lib*.a
files). They provide features as already compiled code that you need to link into your executable.
Read more about linkers
Upvotes: 1