Search code examples
compilationlinkermingwglfw

How to link GLFW in a C program on windows in a makefile


My project structure looks like this.

lib/GLFW/glfw3.h
lib/GLFW/glfw3.dll
lib/GLFW/libglfw3dll.a
main.c
main.exe
makefile

And in my makefile I have this.

gcc main.o -o main -D GLFW_DLL -I lib/GLFW -Llib/GLFW lib/GLFW/libglfw3dll.a -lgdi32

In my main.c file I include it like so.

#include <lib/GLFW/glfw3.h>

Which gives an error when I compile saying it cannot find it.


Solution

  • There are 3 steps that each need specific attention:

    Compiling

    Use the -I flag to add the location(s) where header (.h) files can be found.

    gcc -c -o main.o main.c -DGLFW_DLL -Ilib/GLFW
    

    Linking

    Use the -L flag to add the location(s) where header import libraries (.a or .dll.a) files can be found.

    Use the -l flag to specify the import library file(s) (.a or .dll.a) to link against, leaving out the lib prefix and the extention (.a or .dll.a).

    gcc -o main.exe main.o -Llib/GLFW -lglfw3dll -lgdi32
    

    Note that normally the shared import library should be called libglfw3.dll.a instead of libglfw3dll.a. In that case the flag should be -lglfw3 (which will pick up libglfw3.dll.a if you're not linking statically with the -static flag in which case it would look for libglfw3.a)

    Running

    The .dll file(s) your program is linked against (and the .dll file(s) those .dll file(s) are linked agains, etc.) must be found at runtime.

    To make sure they are found you can:

    • add the location(s) of the .dll file(s) to your PATH environment variable (I don't recommend this).
    • copy the .dll file(s) (in this case glfw3.dll) in the same folder as the .exe file. Tip: you can use copypedeps -r from the pedeps project to do this.