0

I have two different CMake builds: one with emscripten and one with regular g++. Based on the build type I want to execute certain c++ code blocks. I'm not sure how to do that.

CMAKE file:

cmake_minimum_required(VERSION 3.15)
project(project)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra")

if( ${CMAKE_SYSTEM_NAME} MATCHES "Emscripten")
    # build with emscripten
else()
    # build regularly
    find_package(SDL2 REQUIRED)
    find_package(Freetype REQUIRED)
endif()
include_directories(${CMAKE_SOURCE_DIR}/include ${SDL2_INCLUDE_DIRS} ${FREETYPE_INCLUDE_DIRS})

add_executable(project src/main.cpp src/glad.c src/Game.cpp)
target_link_libraries(project ${SDL2_LIBRARIES} ${FREETYPE_LIBRARIES})

In C++ I want to do the following:

if( not_emscripten_build ) {
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
}
Kevin
  • 16,549
  • 8
  • 60
  • 74
Astrejoe
  • 335
  • 2
  • 9
  • Have you considered using a compile definition and surrounding that section of C++ code with an `#ifdef`? See these posts [here](https://stackoverflow.com/q/24488239/3987854) and [here](https://stackoverflow.com/questions/7900661/how-to-read-a-cmake-variable-in-c-source-code), but there are many more like this on the site. – Kevin May 06 '20 at 13:16

2 Answers2

0

CMake variables cannot be accessed in C++. However, CMake can set compiler options, and specifically, macro definitions. Such macros can be accessed by the pre processor. Use the target_compile_definitions command.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

After some trying I came up with the following solutions using compile definitions:


    cmake_minimum_required(VERSION 3.15)
    project(project)

    set(CMAKE_CXX_STANDARD 20)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra")

    if( ${CMAKE_SYSTEM_NAME} MATCHES "Emscripten")
        add_compile_definitions(BUILD_TYPE="emcc")
    else()
        find_package(SDL2 REQUIRED)
        find_package(Freetype REQUIRED)
        add_compile_definitions(BUILD_TYPE="gcc")
    endif()
    include_directories(${CMAKE_SOURCE_DIR}/include ${SDL2_INCLUDE_DIRS} 
    ${FREETYPE_INCLUDE_DIRS})

    add_executable(project src/main.cpp src/glad.c src/Game.cpp)
    target_link_libraries(project ${SDL2_LIBRARIES} ${FREETYPE_LIBRARIES})

In my C++ project I include the following header file:



    #ifndef JUMPYBLOCK_BUILDTYPE_H
    #define JUMPYBLOCK_BUILDTYPE_H
    const bool EM_BUILD = strcmp(BUILD_TYPE, "emcc") == 0;
    #endif //JUMPYBLOCK_BUILDTYPE_H

I can then do the following in C++:



    if( !EM_BUILD) {
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, 
        SDL_GL_CONTEXT_PROFILE_CORE);
    }

Astrejoe
  • 335
  • 2
  • 9