CMake goes into an infinite loop when there are two stand-alone subprojects with two different compilers within the same build

I am new to CMake. What I want to have is two different stand-alone subprojects within one “root” project such that those two subprojects could be built independently. Given that those two subprojects use two different type of compilers.

Let’s start with the directory structure, it looks like this:

project/
├── CMakeLists.txt
├── subproject01
│   ├── CMakeLists.txt
│   └── subproject01.c
└── subproject02
    ├── CMakeLists.txt
    └── subproject02.cpp

The root CMakeLists.txt looks like this:

cmake_minimum_required(VERSION 3.21...3.27 FATAL_ERROR)

project(project DESCRIPTION "A project")

add_subdirectory(subproject01)
add_subdirectory(subproject02)

Here, subproject01 uses gcc/g++ and the corresponding CMakeLists.txt looks like this:

cmake_minimum_required(VERSION 3.21...3.27 FATAL_ERROR)

project(subproject01 DESCRIPTION "A sub-project 01")

add_library(${PROJECT_NAME} MODULE subproject01.c)

install(
    TARGETS ${PROJECT_NAME} LIBRARY DESTINATION project/subproject01
)

Where subproject02 uses clang/clang++ and the corresponding CMakeLists.txt file looks like this:

cmake_minimum_required(VERSION 3.21...3.27 FATAL_ERROR)

set(CMAKE_C_COMPILER "/usr/bin/clang")
set(CMAKE_CXX_COMPILER "/usr/bin/clang++")

project(subproject02 DESCRIPTION "A sub-project 02")

add_library(${PROJECT_NAME} MODULE subproject02.cpp)

install(
    TARGETS ${PROJECT_NAME} LIBRARY DESTINATION project/subproject02
)

I can build those two subprojects independently when I invoke cmake command within their respective subproject directories.

But when I try to build from root project directory, the cmake goes into infinite loop.

How do I achieve this? I want two different stand-alone subprojects within one “root” project such that those two subprojects could be built independently or all at once from the root.

In any case, for reproducibility, subproject01.c looks like this:

#include <stdlib.h>

int function(int);

int function(int a)
{
    return a + 1;
}

and subproject02.cpp looks like this:

#include <iostream>

double function(double a)
{
    return a + 1;
}

Use ExternalProject. Working example: GitHub - scivision/cmake-distinct-compilers: CMake project with different compilers for different directories via ExternalProject

1 Like