Home > Net >  Embed Define into a string
Embed Define into a string

Time:06-27

I have a preprocessor define that should determine the size of an array.
This constant should also be passed to a HLSL shader.
For this I need to pass it around as a string.
Is there a way to embed preprocessor defines as a string?

#include <iostream>
#ifndef SIZE
#define SIZE 16
#endif
int main() {
    const int arr[SIZE] = {}; // array size is 16 :)
    const char* str = "SIZE"; // literal is "SIZE" and not "16" :(
    std::cout << str << std::endl; // should print "16"
    std::cout << SIZE << std::endl; // prints 16, but is not a string
}

CodePudding user response:

You can use a stringifying macro, eg:

#define STRINGIFY(x) STRINGIFY2(x)
#define STRINGIFY2(x) #x

const char* str = STRINGIFY(SIZE);
std::cout << str << std::endl;

Alternatively, use a runtime format via snprintf() or equivalent, eg:

char str[12];
snprintf(str, "%d", SIZE);
std::cout << str << std::endl;

However, you really should be using std::string in C instead of char*, eg:

#include <string>

std::string str = std::to_string(SIZE);
std::cout << str << std::endl;

Or:

#include <string>
#include <sstream>

std::ostringstream oss;
oss << SIZE;
std::cout << oss.str() << std::endl;
  • Related