Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reinterpret_cast<volatile uint8_t*>(37)' is not a constant expression

Tags:

c++

c++11

avr

gcc fails to compile the code below, while clang compiles ok. I have no control on the macro PORTB, as it is in a 3rd party library (avr).

Is it a gcc bug? How can I work around it in gcc? As a workaround is somehow possible to create a pre-processor macro which extracts the numerical value from PORTB?

Note this question is similar, but not identical to my previous question. It is also different from this question, where the developer has the flexibility to change the rhs of the assignment, thus avoiding the reinterpret_cast.

#include <iostream>
#include <cstdint>

#define PORTB (*(volatile uint8_t *)((0x05) + 0x20))

struct PortB {
    static const uintptr_t port = reinterpret_cast<uintptr_t>(&PORTB);
};

int main() {
    std::cout << PortB::port << "\n";
    return 0;
}
like image 822
Fabio Avatar asked Jan 14 '19 01:01

Fabio


1 Answers

It seems reinterpret_cast is not allowed during compilation. Thus the newer version of the compiler simply is more conforming to the language. reinterpret_cast will not be allowed where a constexpr is required.

But maybe these workaround may help (compiles with g++ 9.2):

#include <iostream>
#include <cstdint>

#define PORTB (*(volatile uint8_t *)((0x05) + 0x20))

struct PortB {
    static uintptr_t port; 
};

uintptr_t PortB::port = reinterpret_cast<uintptr_t>(&PORTB);
const uintptr_t freePort = reinterpret_cast<uintptr_t>(&PORTB);
#define macroPort reinterpret_cast<uintptr_t>(&PORTB)

int main() {
    std::cout << PortB::port << "\n";
    std::cout << freePort << "\n";
    std::cout << macroPort << "\n";
    return 0;
}
like image 83
user5534993 Avatar answered Sep 21 '22 06:09

user5534993