mardi 27 août 2019

Union cannot be defined in a type specifier

I try to include a c code library from Github in my C++ application but encountered some compile error.

Errors for the original code:

'_u16' cannot be defined in a type specifier


non-constant-expression cannot be narrowed from type 'int' to 'uint8_t' (aka 'unsigned char') in initializer list [-Wc++11-narrowing]

The application is compiled by Clang 10.0.1 using CMake on macOS with following in CMakeLists.txt:

set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c11")

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

Following is the original code:

inline static void UInt16SetBE(void *b2, uint16_t u)
{
    *(union _u16 { uint8_t u8[16/8]; } *)b2 = (union _u16) { (u >> 8) & 0xff, u & 0xff };
}

Following is my code after adding casting to try to resolve the error:

inline static void UInt16SetBE(void *b2, uint16_t u)
{
    *(union _u16 { uint8_t u8[16/8]; } *)b2 = (union _u16) { (uint8_t)((u >> 8) & 0xff), (uint8_t)(u & 0xff) };
}

Errors after my change:

'_u16' cannot be defined in a type specifier

Does anyone know what the syntax of the declaration means? *(union _u16 { uint8_t u8[16/8]; } *)b2

Aucun commentaire:

Enregistrer un commentaire