A project has the ability to compile code in or not and there is a need to know which code is included and what is not. The functions are all isolated in single files and the code therein is embraced in #ifdef UPPERCASE_FILENAME_C ...code... #endif and to make handling it simpler we check with a bit of preprocessor "magic"
#define STRINGIZE(x) __STRINGIZE(x)
#define __STRINGIZE(x) ""#x""
#define MP_HAS(x) (sizeof(STRINGIZE(x##_C)) == 1u )
If the macro in question is defined, it expands to an empty string which has a size of one (only the \0 gets counted) and if not the whole string given gets expanded which resolves to a value >1.
Something to play around with:
#include <stdlib.h>
#include <stdio.h>
#ifdef DEFINE_IT
#define FOOT_C
#endif
#define STRINGIZE(x) __STRINGIZE(x)
#define __STRINGIZE(x) ""#x""
#define HAVE_WE(x) (sizeof(STRINGIZE(x##_C)) )
int main(void) {
printf("sizeof(stringized) = %zu\n", HAVE_WE(FOOT));
exit(EXIT_SUCCESS);
}
So far, so good. A bit complicated, but it works.
But: if we give the definition at the commandline (to test all branches)gcc -DFOOT_C sizeoftest.c -o sizeoftest the macro expands to 1, so the string is not empty anymore and has a sizeof of 2 (two), the character 1 and the character \0.
One workaround is to set the definition given at commandline to an empty string explicitely: gcc -DFOOT_C="" sizeoftest.c -o sizeoftest.
Is there a way to adapt the stringify macros to ignore that discrepancy and handle both ways to define a macro in the same way?
EDIT: The proposed answer at Check at runtime if macro was defined does not fit exactly, sadly, but it came close. Might be the right direction.
#ifdef FOOT_C ...?ifdef's. Not much of a problem, but I thought someone here could show a more elegant way to do it. The answer linked by @nielsen for example seems promising.The functions are all isolated in single files and the code therein is embraced in #ifdef UPPERCASE_FILENAME_CGreat, so what is the point of the question?__STRIidentifiers starting with double_are reserved, you can't use them.