Skip to content

Cmake position-indepentent code #35

@jvillasante

Description

@jvillasante

In Chapter 7 we get introduced to the following CMake function to compile with position-independent code enabled:

function(add_test_cpp_target name)
    add_executable(${name} "${name}.cpp")
    target_compile_options(${name} PRIVATE -g -O0 -pie)
    add_dependencies(tests ${name})
endfunction()

However, that didn't work for me in Fedora as shown here after compiling with that function:

readelf -h build/test/targets/hello_sdb | grep 'Type:'
  Type:                              EXEC (Executable file)

When I changed the previous function to the followng:

function(add_test_cpp_target name)
    add_executable(${name} "${name}.cpp")

    # Add -fPIC for the compiler
    target_compile_options(${name} PRIVATE -g -O0 -fPIC)

    # Add -pie for the linker
    target_link_options(${name} PRIVATE -pie)

    # target_compile_options(${name} PRIVATE -g -O0)
    add_dependencies(tests ${name})
endfunction()

It appears to work again as shown below. The explanation is in the comment (apparently you need one flag for the compiler and another for the linker):

readelf -h build/test/targets/hello_sdb | grep 'Type:'
  Type:                              DYN (Position-Independent Executable file)

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions