I have a header file of constants shared among both C++ and C executables. I don’t want to duplicate the constants which I want as constexpr
in C++ and #define
s in C.
<code>
// shared_header.h
#pragma once
#if __cplusplus
#define CONST constexpr
#else
#define CONST const // not a good enough
#endif
CONST int my_constant = 1;
</code>
<code>
// shared_header.h
#pragma once
#if __cplusplus
#define CONST constexpr
#else
#define CONST const // not a good enough
#endif
CONST int my_constant = 1;
</code>
// shared_header.h
#pragma once
#if __cplusplus
#define CONST constexpr
#else
#define CONST const // not a good enough
#endif
CONST int my_constant = 1;
A more sophisticated, but uglier approach,
<code>#if __cplusplus
#define CONST(name, val) constexpr int name = val;
#else
#define CONST(name, val) #define name val;
#endif
CONST(my_constant, 1)
</code>
<code>#if __cplusplus
#define CONST(name, val) constexpr int name = val;
#else
#define CONST(name, val) #define name val;
#endif
CONST(my_constant, 1)
</code>
#if __cplusplus
#define CONST(name, val) constexpr int name = val;
#else
#define CONST(name, val) #define name val;
#endif
CONST(my_constant, 1)
.. which doesn’t compile (for multiple reasons).
But surely there is a smart may to do this without having to duplicate all constants, once for C++ and once for C?