How to add Compiler Flag in CMakeLists Clion for shm_open()

Answered

Simple Programm:

#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>

int main() {
int shm_fd;

shm_fd=shm_open("sh",O_CREAT|O_RDWR,0666);
return 0;
}

The error is:

Warning: undefined reference to »shm_open«
collect2: error: ld returned 1 exit status
CMakeFiles/Share_Memory_Project.dir/build.make:102: recipe for target 'Share_Memory_Project' failed
make[3]: *** [Share_Memory_Project] Error 1
CMakeFiles/Makefile2:94: recipe for target 'CMakeFiles/Share_Memory_Project.dir/all' failed
make[2]: *** [CMakeFiles/Share_Memory_Project.dir/all] Error 2
CMakeFiles/Makefile2:101: recipe for target 'CMakeFiles/Share_Memory_Project.dir/rule' failed
make[1]: *** [CMakeFiles/Share_Memory_Project.dir/rule] Error 2
Makefile:137: recipe for target 'Share_Memory_Project' failed
make: *** [Share_Memory_Project] Error 2

To fix this Problem, I have to add a Compiler Flag: -lrt at the end. Like this: gcc main.c -o main -lrt. So When I put this in Command Line at Ubuntu Terminal it compile fine.

My Question is: How to add this Flag at my CMakeLists.txt in Clion?

How my file currently looks:

cmake_minimum_required(VERSION 3.19)
project(Share_Memory_Project C)

set(CMAKE_C_STANDARD 99)

add_executable(Share_Memory_Project main.c)
0
2 comments

Have you tried this:

target_compile_options(Share_Memory_Project PRIVATE -lrt)
1

Also you can try to link the rt library this way:

find_library(LIBRT rt)                                                                                                                                                                                                                                                                                        
if(LIBRT)
target_link_libraries(Share_Memory_Project ${LIBRT}) 
endif()
0

Please sign in to leave a comment.