I recently made a small library in C, and I wanted to put it together with the standard libraries so I don't have to always copy the files for each new project. Where do I have to put it so I can import it like the standard libraries?
Compiler : MinGW
OS: Windows
CodePudding user response:
You need to create a library, but you don't necessarily need to put it in the same place as MinGW's standard libraries (in fact I think that's a bad idea).
It is better to put your own library/libraries in specific place and then use the -I
compiler flag to tell the compiler where to find the header files (.h
, .hpp
, .hh
) and the -L
linker flag to tell the linker where to find the library archives (.a
, .dll.a
). If you have .dll
files you should make sure they are in your PATH
environment variable when you run your .exe
or make sure the .dll
files are copied in the same folder as your .exe
.
If you use an IDE (e.g. Code::Blocks or Visual Studio Code) you can set these flags in the global IDE compiler/linker settings so you won't have to add the flags for each new project.
Then when building a project that uses your library you will need to add the -l
flag with the library name to your linker flags, but without the lib prefix and without the extension (e.g. to use libmystuff.a
/libmystuff.dll.a
specify linker flag -lmystuff
). The use of the -static
flag will tell the linker to use the static library instead of the shared library if both are available.
I have created a minimal example library at https://github.com/brechtsanders/ci-test to illustrate on how to create a library that can be build both as static and shared (DLL) library on Windows, but the same code also compiles on macOS and Linux.
If you don't use build tools like Make or CMake and want do the steps manually they would look like this for a static library:
gcc -c -o mystuff.o mystuff.c
ar cr libmystuff.a mystuff.c
To distribute the library in binary form you should distribute your header files (.h
) and the library archive files (.a
).
CodePudding user response:
Here's an example, from a Makefile
:
Create Library
@clang -c $(LIBRARY_COMPILER_FLAGS) $(LIBRARY_DEFINES) $(LIBRARY_INCLUDE_PATHS) $(LIBRARY_SOURCES)
@ar rcs $(LIBRARY) *.o
Link Library
@clang -c $(APPLICATION_COMPILER_FLAGS) $(APPLICATION_DEFINES) $(APPLICATION_INCLUDE_PATHS) $(APPLICATION_SOURCES)
@clang *.o -o $(EXECUTABLE) $(LIBRARY)