Initializing a const variable with ntohl ()

I am trying to initialize a const variable with global scope with a value that is appropriately replaced with bytes.

#include <stdio.h>
#include <stdint.h>
#include <arpa/inet.h>

const uint32_t a = ntohl(0x11223344);

int main(int argc, char const *argv[])
{
    printf("%08x\n", a);
    return 0;
}

With gcc, this does not work with "error: initializer element is not constant". Yes, that’s good, so the gcc header has ntohl () defined as a function, or as "do {...} while (0)" or something similar that cannot be evaluated at compile time. Bummer.

Is there anything I can do to achieve the same goal? I need to initialize the value for the corresponding limb, and I want it to be a global area. Is there any way to convince gcc to do this, with the exception of pitching my own ntohl-like macro?

(, , clang ntohl(), , . clang. , .)

+4
2

main() - ( Linux):

 #include <endian.h>
 #if __BYTE_ORDER == __LITTLE_ENDIAN
 const uint32_t a = 0x44332211;
 #else
 const uint32_t a = 0x11223344;
 #endif

, ,

 #include <endian.h>
 #define A_ADDR 0x11223344
 #if __BYTE_ORDER == __LITTLE_ENDIAN
 const uint32_t a = __bswap_constant_32(A_ADDR);
 #else
 const uint32_t a = A_ADDR;
 #endif
+2

6.7.8/4

.

ntohl , . .

, , . , , , ,

void foo(void)
{
  const unit32_t a = ntohl(0x11223344);
  /* ... */
}

, ,

#define POTRZEBIE ntohl(0x11223344)

void bar(void)
{
  const unit32_t a = POTRZEBIE;
  /* ... */
}

const , .

+3

Source: https://habr.com/ru/post/1526838/


All Articles