Cmake definitions

Hello,
Can I add conditional definitions in CmakeListUser.txt used by pio run command?

My cmake code:

if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/src/forceCfg.h)
  add_compile_definitions(FORCE_CFG)
endif()

Thanks.

PS: Sory for my bad english.

In every case but framework = espidf the CMakeLists.txt generated by PlatformIO is just used to transport code intellisense information. All building is done by PlatformIO (pio run). If you want to add build logic into the project correctly, you have to do it via the platformio.ini, not the CMakeLists(User), e.g. via build_flags or scripting.

I understand, and am I able to do a similar maneuver directly in pio?

Define “simple maneuver”? Adding compile flags? Yes, via the platformio.ini I already linked above.

I have a configuration in a dedicated file that I force for the development time, and I would like it to be automatically included in the compilation when it exists by defining a macro variable

So you want to do a build_flags = -include src/forceCfg.h?

In my main.cpp file I have code:

#ifdef FORCE_CFG
  #include "forceCfg.h"
#endif

void setup(){
//...
#ifdef FORCE_CFG
  force(eeprom);
#endif
//...
}

but file src/forceCfg.h is optional, if this file exists I would to create macro FORCE_CFG.
include parameter requires the file to exist.

PS: I tried to check with a python script, with - and without

Import("env")
env.Append(CCFLAGS=["DFORCE_CFG"])
env.Append(CFLAGS=["DFORCE_CFG"])
env.Append(CXXFLAGS=["DFORCE_CFG"])

Why not the other way around? You can create an environement which uses build_flags = -DFORCE_CFG to create the macro, and based on that, the code will try to include src/forceCfg.h, and another environment which does not do that.

Or, if you really want to script it,

platformio.ini

[env:uno]
platform = atmelavr
board = uno
framework = arduino
extra_scripts = pre:force_cfg.py

force_cfg.py

from os.path import isfile, join
Import("env")

file_path = join(env.subst("$PROJECT_SRC_DIR"), "forceCfg.h")
if isfile(file_path):
    print("File exists, defining Macro")    
    env.Append(CPPDEFINES=[("FORCE_CFG")])

src/main.cpp

#include <Arduino.h>
#ifdef FORCE_CFG
#warning FORCE_CFG was defined
#else
#warning FORCE_CFG was not defined
#endif

#ifdef FORCE_CFG
  #include "forceCfg.h"
#endif

void setup(){}
void loop() {}

src/forceCfg.h

#pragma once

#define SOMETHING 123

When src/forceCfg.h exists, compiles as

src\main.cpp:3:2: warning: #warning FORCE_CFG was defined [-Wcpp]
 #warning FORCE_CFG was defined
  ^~~~~~~

When it is renamed to something else, compiles as

src\main.cpp:5:2: warning: #warning FORCE_CFG was not defined [-Wcpp]
 #warning FORCE_CFG was not defined
  ^~~~~~~
1 Like