3.9. Executables

Examples on GitHub

CMake documentation

3.9.1. Simple

Building executable from main.cpp:

cmake_minimum_required(VERSION 2.8)
project(foo)

add_executable(foo main.cpp)
[executable-examples]> rm -rf _builds
[executable-examples]> cmake -Hsimple -B_builds
-- The C compiler identification is GNU 5.4.0
-- The CXX compiler identification is GNU 5.4.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
-- Configuring done
-- Generating done
-- Build files have been written to: /.../executable-examples/_builds
[executable-examples]> cmake --build _builds
Scanning dependencies of target foo
[ 50%] Building CXX object CMakeFiles/foo.dir/main.cpp.o
[100%] Linking CXX executable foo
[100%] Built target foo
[executable-examples]> ./_builds/foo
Hello from CGold!

3.9.2. Duplicates

Targets are global, you can’t declare two targets with the same name even if they are declared in different CMakeLists.txt:

# top-level CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
project(foo)

add_subdirectory(boo)
add_subdirectory(bar)
# boo/CMakeLists.txt

add_executable(foo main.cpp)
# bar/CMakeLists.txt

add_executable(foo main.cpp)
[examples]> rm -rf _builds
[examples]> cmake -Hexecutable-examples/duplicates -B_builds
-- The C compiler identification is GNU 5.4.0
-- The CXX compiler identification is GNU 5.4.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 Error at bar/CMakeLists.txt:1 (add_executable):
  add_executable cannot create target "foo" because another target with the
  same name already exists.  The existing target is an executable created in
  source directory
  "/.../executable-examples/duplicates/boo".
  See documentation for policy CMP0002 for more details.