Introduction
I have a class (EagerSingleton
) that is written in eager-loaded singleton pattern (class is instantiated in the source file). Class is located in a library my_lib
(see Example of the CMake build system generator). The class instantiates itself and is meant to run in the background, without any user interaction.
Expected behavior
Instance is instantiated and the onRun()
(see example of the eager-loaded singleton used) member function is called after the FreeRTOS scheduler is called.
Realized behavior
Looking into the final executable (.elf), there are no references to the EagerSingleton
. Furthermore, after the FreeRTOS scheduler is started, other parts of the application start working, but not this singleton. It should also be noted, inspecting the static library libmy_lib.a
, that EagerSingleton is compiled into the libmy_lib.a
, but is obviously omitted from the final executable.
Additional information
This project also has a makefile build system that works perfectly with this software design. My guess is, since makefile system builds everything together (and doesn't separate everything into libraries) it doesn't optimize the class, where the CMake sees that this class is not referenced anywhere and for that reason it removes it.
Question
Is this behavior expected? Best way to fix this issue?
Example of the eager-loaded singleton used
// eager_singleton.hpp
// This class is only for the problem demonstration!
#pragma once
class EagerSingleton
{
public:
EagerSingleton getInstance()
{
return instance;
}
private:
static EagerSingleton instance;
EagerSingleton();
void onRun();
};
// eager_singleton.cpp
// This class is only for the problem demonstration!
#include "eager_singleton.hpp"
EagerSingleton EagerSingleton::instance {};
EagerSingleton::EagerSingleton() : xTaskCreateStatic(...) // Passing a member function onRun().
{}
void onRun()
{
// Do stuff.
}
It must be noted that, with this design, no code referencing this class is needed in the main application.
Example of the CMake build system generator
# <Project root>/lib/CMakeLists.txt
# Library containing eager_singleton.
add_library(my_lib)
target_sources(my_lib PRIVATE
${CMAKE_CURRENT_LIST_DIR}/src/eager_singleton.cpp)
target_include_directories(my_lib PUBLIC
${CMAKE_CURRENT_LIST_DIR}/include)
# <Project root>/CMakeLists.txt
cmake_minimum_required(VERSION 3.16.3)
project(test_project)
set(CMAKE_CXX_STANDARD 20)
add_executable(test_project main.cpp)
add_subdirectory(lib)
target_link_libraries(test_project PRIVATE
my_lib)
target_compile_options(test_project PRIVATE
-Wall
-Wextra
-pedantic)