Access to static global variables in a built-in function

I had a strange problem, I narrowed down to the following test case:

inl.h:

inline const char *fn() { return id; }

a.cc:

#include <stdio.h>

static const char *id = "This is A";

#include "inl.h"

void A()
{
    printf("In A we get: %s\n", fn());
}

b.cc:

#include <stdio.h>

static const char *id = "This is B";

#include "inl.h"

void B()
{
    printf("In B we get: %s\n", fn());
}

extern void A();

int main()
{
    A();
    B();
    return 0;
}

Now when I compile this with help g++ -O1 a.cc b.cc, it works correctly. I get:

In A we get: This is A
In B we get: This is B

but if I compile with g++ -O0 a.cc b.cc, I get:

In A we get: This is A
In B we get: This is A

Note that I'm actually trying to use the C11 semantics here, but I am using g ++, since gcc does not yet support C11.

Now, as far as I can tell, looking at both the C11 spec and the C ++ spec (C ++ 11 and older specs - the semantics of the built-in and static global variables don't seem to have changed), it should do what I want, and failure to use -O0is a bug in gcc.

, - - , , undefined?

Edit

, , , fn static . 6.7.4.6 C99 (6.7.4.7 C11 - ++):

extern, . , .

, extern, . static .

C, - ++, static .

+5
2

. fn - . id, a.cc, , id b.cc. , , , , inline, undefined.

++, C, , C11, , ++. ++ 11 (at & sect. 3.2/5), , , fn id ( ):

& hellip; (7.1.2) & hellip; , , , . D, ,

  • D ;
  • D, , 3.4, , D , (13.3) (14.8.3), , const , D, (5.19) ( ) , D;
  • & hellip;

fn , id, D, . ++ , . ++ 11 & sect; 7.1.1/7 :

, , , - , const.

, undefined, , .

+8

fn() static, @RobKennedy, UB. -O0, , inlining, , , , -. A , , , . -O1, , , , , , () .

+3

All Articles