Search code examples
c++volatile

How do I get a volatile function argument working?


I am completely unexperienced in C++, I use C all the time. In my recent hobby project I need to mix in a C++ library with my C code thus forcing me to have a C++ main.cpp.

I am right now meddling my C code to compile as C++. This even works pretty well except for one problem I simply cannot solve.

This is an interrupt service incrementing my unix time variable every second and also doing a conversion into spli-up time format afterwards. Since this happens in an interrupt I set the variables as volatile.

volatile time_t UNIX_TIME = 0;
volatile struct tm TIME_CUR_LOCALTIME;  

if (htim == &htim2){
    UNIX_TIME++;
    TIME_CUR_LOCALTIME = *localtime(&UNIX_TIME);
}

From library time.h:

struct tm *localtime (const time_t *_timer);

With gcc this compiles flawless.

g++ is a different story. It gives me the error:

error: passing 'volatile tm' as 'this' argument discards qualifiers [-fpermissive]

I tried multiple casts and stuff, the only way this starts working by itself is when I drop both volatile qualifiers. But I don't want that.

What is the correct way to get this working? I am out of ideas.


Solution

  • Copy the time first into a non-volatile instance:

    time_t t = UNIX_TIME;
    tm local = *localtime(&t);
    TIME_CUR_LOCALTIME.tm_sec   = local.tm_sec;
    TIME_CUR_LOCALTIME.tm_min   = local.tm_min;
    TIME_CUR_LOCALTIME.tm_hour  = local.tm_hour;
    TIME_CUR_LOCALTIME.tm_mday  = local.tm_mday;
    TIME_CUR_LOCALTIME.tm_mon   = local.tm_mon;
    TIME_CUR_LOCALTIME.tm_year  = local.tm_year;
    TIME_CUR_LOCALTIME.tm_wday  = local.tm_wday;
    TIME_CUR_LOCALTIME.tm_yday  = local.tm_yday;
    TIME_CUR_LOCALTIME.tm_isdst = local.tm_isdst;