1
0
mirror of https://gitlab.com/bzip2/bzip2.git synced 2026-10-23 09:48:56 +03:00

CMake: Option to build static library with PIC, default ON

The static library must be compiled with POSITION_INDEPENDENT_CODE=ON in
order to link it into shared libraries.

But some compilers cannot generate position independent code for static
libraries.

To solve for both use cases, this commit adds a new CMake option
`ENABLE_STATIC_LIB_IS_PIC` that is ON by default.

You may need to build with `-D ENABLE_STATIC_LIB_IS_PIC=OFF` if your
compiler fails to generate position independent code when compiling the
static library.

Resolves: https://gitlab.com/bzip2/bzip2/-/issues/47
This commit is contained in:
Micah Snyder
2023-05-31 15:02:46 -07:00
parent 2d8393924b
commit 215b326c25
3 changed files with 22 additions and 1 deletions

View File

@@ -305,8 +305,10 @@ if(ENABLE_SHARED_LIB)
${CMAKE_CURRENT_SOURCE_DIR}/libbz2.def
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/bzlib_private.h
INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/bzlib.h)
# Always use '-fPIC'/'-fPIE' option for shared libraries.
set_property(TARGET bz2 PROPERTY POSITION_INDEPENDENT_CODE ON)
set_target_properties(bz2 PROPERTIES
COMPILE_FLAGS "${WARNCFLAGS}"
VERSION ${LT_VERSION} SOVERSION ${LT_SOVERSION})
@@ -321,7 +323,7 @@ if(ENABLE_SHARED_LIB)
add_library(bz2_old_soname SHARED ${BZ2_RES})
target_sources(bz2_old_soname
PRIVATE ${BZ2_SOURCES}
${CMAKE_CURRENT_SOURCE_DIR}/libbz2.def
${CMAKE_CURRENT_SOURCE_DIR}/libbz2.def
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/bzlib_private.h
INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/bzlib.h
)
@@ -342,6 +344,13 @@ if(ENABLE_STATIC_LIB)
PRIVATE ${BZ2_SOURCES}
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/bzlib_private.h
INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/bzlib.h)
# Use '-fPIC'/'-fPIE' option for static libraries by default.
# You may build with ENABLE_STATIC_LIB_IS_PIC=OFF to disable PIC for the static library.
if(ENABLE_STATIC_LIB_IS_PIC)
set_property(TARGET bz2_static PROPERTY POSITION_INDEPENDENT_CODE ON)
endif()
set_target_properties(bz2_static PROPERTIES
COMPILE_FLAGS "${WARNCFLAGS}"
VERSION ${LT_VERSION}

View File

@@ -23,3 +23,5 @@ option(ENABLE_STATIC_LIB "Build libbz2 in static mode also")
option(ENABLE_SHARED_LIB "Build libbz2 as a shared library" ON)
option(USE_OLD_SONAME "Use libbz2.so.1.0 for compatibility with old Makefiles" OFF)
option(ENABLE_STATIC_LIB_IS_PIC "Enable position independent code for the static library" ON)

View File

@@ -269,3 +269,13 @@ mkdir build && cd build
cmake .. -DUSE_OLD_SONAME=ON
cmake --build .
```
`ENABLE_STATIC_LIB_IS_PIC`: Default: `ON`
Disabling this option will make it so that building the static library will not
use the '-fPIC'/'-fPIE' compiler options. You may need to disable this option if
your compiler cannot generate position-independent code for your platform. E.g.:
```sh
mkdir build && cd build
cmake .. -DENABLE_STATIC_LIB_IS_PIC=OFF
cmake --build .
```