GCC -O2 and __ attribute __ ((weak))

It seems that with the GCC -O2and __attribute__((weak))produces different results depending on whether you are referring to their weak characters. Consider this:

$ cat weak.c

#include <stdio.h>

extern const int weaksym1;
const int weaksym1 __attribute__(( weak )) = 0;

extern const int weaksym2;
const int weaksym2 __attribute__(( weak )) = 0;

extern int weaksym3;
int weaksym3 __attribute__(( weak )) = 0;

void testweak(void)
{
    if ( weaksym1 == 0 )
    {
        printf( "0\n" );
    }
    else
    {
        printf( "1\n" );
    }

    printf( "%d\n", weaksym2 );


    if ( weaksym3 == 0 )
    {
        printf( "0\n" );
    }
    else
    {
        printf( "1\n" );
    }
}

$ cat test.c

extern const int weaksym1;
const int weaksym1 = 1;

extern const int weaksym2;
const int weaksym2 = 1;

extern int weaksym3;
int weaksym3 = 1;

extern void testweak(void);

void main(void)
{
    testweak();
}

$ make

gcc  -c weak.c
gcc  -c test.c
gcc  -o test test.o weak.o

$. / test

1
1
1

$ make ADD_FLAGS = "- O2"

gcc -O2 -c weak.c
gcc -O2 -c test.c
gcc -O2 -o test test.o weak.o

$. / test

0
1
1

The question is why the last "./test" produces "0 1 1" and not "1 1 1"?

gcc version 5.4.0 (gcc)

+4
source share
2 answers

It seems that when performing optimizations, the compiler has problems with declared characters constand with the definition weakin one compilation unit.

You can create a separate file c and move weak const definitions there, this will solve the problem:

weak_def.c

const int weaksym1 __attribute__(( weak )) = 0;
const int weaksym2 __attribute__(( weak )) = 0;

, : GCC

+2

:

, . ( , ).

, , OP, C . ; () .

, (= 0) , :

extern const int weaksym1;
const int weaksym1 __attribute__((__weak__));

extern const int weaksym2;
const int weaksym2 __attribute__((__weak__));

extern int weaksym3;
int weaksym3 __attribute__((__weak__));

:

C " ". , ELF, () , ELF.

man 1 nm "V",

, . undefined , .

, , . ( "" man 1 nm , ELF.)

" " C. , C "" "" .

, C, "" , C . , , , , / .

, " " , , "" , .

+1

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


All Articles