0

Considering that macros in C are processed by the preprocessor before compiling the project, as well as what is in macros with variables, etc. work as with text, is it possible in some way to add another to one line, but in such a way that it is performed at the level of complementing the source code, and not at runtime?

Example:

#define VERSION_CODE "1.0"

#define ADD_VERSION(base) (base!" !"VERSION_CODE)

int main() {
    printf(ADD_VERSION("MyProgram"));
    return 0;
}

Here, the !" symbol denotes the removal of the quote to the right of the argument and to the left of the existing line. I would not like to perform this action at runtime, since all the constituent strings are already known.

Alex A.
  • 422
  • 3
  • 12
  • Don't do this. Version numbers should not be hard-coded, but should be derived from the build system. – William Pursell Jul 28 '21 at 12:03
  • @William Pursell Here the version was written in the same file purely for example. In a real project, this might come from make or cmake, but similarly using the name of the macro. – Alex A. Jul 28 '21 at 12:11

1 Answers1

1

You don't need to remove the quotes to do this - the compiler will remove them by itself. One of the features of the C-compiler is that it itself does the concatenation of literal strings. This works in both C and C ++.

You can write like this:

#define VERSION_CODE "1.0"

#define ADD_VERSION(base) (base VERSION_CODE)

int main() {
    printf(ADD_VERSION("MyProgram"));
    return 0;
}

As a result, you will receive the following output:

MyProgram1.0
Alex A.
  • 422
  • 3
  • 12