简体   繁体   中英

convert sizeof() value to string in preprocessing time

I have to combine C code with some inline assembly.

I allready have simple mechanism converting my enum values and macros into strings:

#define STR(x) #x
#define DEF2STR(x) STR(x)

"string1 " DEF2STR(MACRO_VALUE_2) " string2"

output string after preprocessing is: "string1 2 string2"

Question is, how can I append sizeof(type) value into string? Thanks.

You can't - sizeof(type) will be evaluated after macro substitutions have taken place... later in the compilation phases.

Why are you trying to do that? Maybe there's another way to get what you really want done....

This solution should be portable:

#include <stdio.h>
#include <limits.h>

#define STR1 "string1 "
#define STR2 " string"

#if (ULONG_MAX == 0xFFFFFFFFu)
  #define LONGSIZE "4"
#elif (ULONG_MAX == 0xFFFFFFFFFFFFFFFFu)
  #define LONGSIZE "8"
#endif

#define STR STR1 LONGSIZE STR2

int main()
{
  puts (STR);
}

You can do it with generic programming, building an array by recursively inheriting a templated struct with an int (or better size_t) template parameter which you divide by 10 and add the right character to the array building onto itself.

It won't be pretty though.

Interesting problem, so I wrote this compile time int to string "function". Note that you can't do this with macors. I've done it with constexpr (C++11, tested with gcc 4.7) and templates.

typedef unsigned int uint;

// number of decimal digits in a number
constexpr int length(uint num) {
    return num ? (length(num / 10) + 1) : 0;
}

uint constexpr decShift(uint num, int n) {
    return n <= 0 ? num : decShift(num/10, n-1);
}

// return '\0' or the nth decimal digit of num
char constexpr intChar(uint num, int index) {
    return index < 0 ? 0 : ( (decShift(num, index) % 10) + '0' );
}

// templated short array of char containing the digits
template<uint num> struct intToStr {
    static constexpr uint n = length(num);
    static constexpr char value[16] = {
        intChar(num, n - 1),
        intChar(num, n - 2),
        intChar(num, n - 3),
        intChar(num, n - 4),
        intChar(num, n - 5),
        intChar(num, n - 6),
        intChar(num, n - 7),
        intChar(num, n - 8),
        intChar(num, n - 9),
        intChar(num, n - 10),
        intChar(num, n - 11),
        intChar(num, n - 12),
        intChar(num, n - 13),
        intChar(num, n - 14),
        intChar(num, n - 15),
        0
    };
};
template<uint num> constexpr char intToStr<num>::value[16];

// test with sizeof
int main() {
    char array[1357];
    std::cout << intToStr<sizeof(array)>::value << std::endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM