CMake-based build for Simulink coder based project

This CMake config works to compile a Simulink model using the Simulink Coder. It’s based on the C and/or C++ source files generated by the Simulink Coder.

cmake_minimum_required(VERSION 3.10)
# This MUST be equivalent to the Simulink model name
project(my_project)

# Set MATLAB directory
set(MATLAB_DIR "/opt/matlab/v40/")

# Sources we need to pull in from matlab
set(MATLAB_SOURCES
    ${MATLAB_DIR}rtw/c/src/rt_matrx.c
    ${MATLAB_DIR}rtw/c/src/rt_printf.c
    ${MATLAB_DIR}rtw/c/src/rt_logging.c
    ${MATLAB_DIR}rtw/c/src/common/rt_malloc_main.c
)
# Collect all .c and .cpp files in the current directory
file(GLOB SOURCES "*.c" "*.cpp" ${MATLAB_SOURCES})

# Set compiler flags
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pedantic -Wno-long-long -fwrapv -fPIC -O2")


# Include directories
include_directories(
    .
    ${MATLAB_DIR}extern/include
    ${MATLAB_DIR}simulink/include
    ${MATLAB_DIR}rtw/c/src
    ${MATLAB_DIR}rtw/c/src/ext_mode/common
)
# Add executable
add_executable(my_project ${SOURCES})

target_compile_definitions(my_project PUBLIC
    CLASSIC_INTERFACE=0
    ALLOCATIONFCN=1
    MAT_FILE=1
    ONESTEPFCN=1
    TERMFCN=1
    MULTI_INSTANCE_CODE=1
    INTEGER_CODE=0
    MT=0
    TID01EQ=0
    RT_MALLOC
    MODEL=my_project
    NUMST=2
    NCSTATES=0
    HAVESTDIO
    RT
    USE_RTMODEL
    UNIX
)

# Linker flags
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-rpath,${MATLAB_DIR}bin/glnxa64 -L${MATLAB_DIR}bin/glnxa64")

# Link libraries
target_link_libraries(my_project m)