Reputation: 2285
I am trying to build static library of project stb, so I can link it in another project (not written in C/C++).
I have created CMakeLists.txt file to build it using CMake, however the built static library file is empty.
I am suspecting this is due to fact that the stb seems to be header-only library. I tried setting the LIBRARY_HEADER_ONLY
flag with target_compile_definitions
, this however did not solve my problem.
How can I build header-only library to static library file (*.a)? Or is it even possible? If not, what are workarounds if any?
This is my CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(stb C)
set(MAKE_GENERATOR_PLATFORM x64)
set(CMAKE_C_FLAGS -m64)
set(CMAKE_CXX_FLAGS -m64)
option(STB_IMAGE_IMPLEMENTATION "stb_image implementation" ON)
if(STB_IMAGE_IMPLEMENTATION)
add_definitions(-DSTB_IMAGE_IMPLEMENTATION)
endif()
option(POSITION_INDEPENDENT_LIB "Use position independent code for static library (if applicable)" ON)
set(SOURCE_FILES stb_image.h stb_truetype.h stb_dxt.h)
add_library(stb_static STATIC ${SOURCE_FILES})
target_compile_definitions(stb_static PUBLIC LIBRARY_HEADER_ONLY)
set_target_properties(stb_static PROPERTIES LINKER_LANGUAGE C)
set_target_properties(stb_static PROPERTIES
OUTPUT_NAME stb
POSITION_INDEPENDENT_CODE ${POSITION_INDEPENDENT_LIB})
Upvotes: 1
Views: 3867
Reputation: 2285
To get an object files and build a static library from the header-only library the extra .c
file must exists. This is because .c
files are the ones which contains instructions and code.
Different toolchains may interpret .h
file differently so the easy and portable way to create the implementation is to create a new .c
file.
#define STB_IMAGE_IMPLEMENTATION
#define STB_DXT_IMPLEMENTATION
#define STB_TRUETYPE_IMPLEMENTATION
#include "stb_image.h"
#include "stb_dxt.h"
#include "stb_truetype.h"
Including the header files (stb_image.h
) and defining the requried macros (STB_IMAGE_IMPLEMENTATION
) in the .c
file is the solution to get object files and static library (with proper content) out of the build.
Upvotes: 4