Are there directives in C/C++ preprocessor to convert string to number?

c, c-preprocessor, preprocessor-directive

Solution

If you need to interact with the pre-processor to set other `#defines` or conditionally `#include` different headers. Until you can get VERSION to be "fixed" to be an integer...

The only thing that I can think of for you to do is to create a tiny header file defining PROPER_VERSION and include it by naming each file as the version number. So here you would create:

100:
#define PROPER_VERSION 100

101:
#define PROPER_VERSION 101

102:
#define PROPER_VERSION 102

and then you would need to add the following:

#include VERSION

And then use `PROPER_VERSION` as you need

#if PROPER_VERSION > 100
...

Its not elegant, but I cannot see anything else you can do. You can auto-generate the VERSION file.

Problem

I wish to add some conditional directive in my code to control different build, for example: ``` #if VERSION > 100 /* Compiling here */ #endif ``` The problem is that 'VERSION' is in other's code where I can't change. It was defined as a string: ``` #define VERSION "101" ``` I'm wondering if there's some sort of macro or directive which converts the string to number so I can simply do ``` #if STRING_TO_NUMBER(VERSION) > 100 /* Compiling here */ #endif ``` Is that possible please? PS. It seems my description is not quite clear. The main purpose of this requirement is to control the version branch. For example, in old version, pre-version 100, this program would like old_function(). After this version, all functions have been migrated to new_function. So I need to write codes like that: ``` #if VERSION >= 100 old_function(); #else new_function(); #endif #if VERSION >= 100 int old_function() { ... } #else int new_function() { ... } #endif ``` You can see that only one of the function will be compiled. Therefore the condition must be decided in preprocessing stage, not in the runtime. The tricky part is, the VERSION had been defined as a string, which brought this question.

Original source

Related problems