Skip to content

cmake picks up environment variables (CFLAGS, LDFLAGS etc.)

cmake picks up environment variables like CFLAGS and LDFLAGS and passes that information to the compiler and linker. This behavior is quite undesirable and makes it more difficult to get reproducible builds. It does not make sense that an environment variable impacts the build result and even takes precedence over a toolchain file.

To see cmake picking up environment variables, do the following

  1. Create a CMakeLists.txt file
project(helloworld)
message(STATUS "CMAKE_EXE_LINKER_FLAGS=${CMAKE_EXE_LINKER_FLAGS}") 
  1. Set LDFLAGS in enviroment
 export LDFLAGS=-Wl,-O1
  1. Configure the build tree
$ cmake ../
-- The C compiler identification is GNU 9.3.0
-- The CXX compiler identification is GNU 9.3.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc - works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ - works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- CMAKE_EXE_LINKER_FLAGS=-Wl,-O1
-- Configuring done
-- Generating done
-- Build files have been written to: /usr/local/src/cmake_example/build
$

Note how cmake picked up the environment variable LDFLAGS and included that in CMAKE_EXE_LINKER_FLAGS.

Passing a toolchain file does not help. Setting CMAKE_EXE_LINKER_FLAGS_INIT requires it to be passed before project, but that is not always feasible.

Is there any way to tell cmake to obey the toolchain file and ignore the environment?

To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information