Weak GCC attribute for constant variables

I have a question regarding a weak attribute of a constant variable. I have the following couple of files compiled with gcc:

main.c:

#include <stdio.h>

const int my_var __attribute__((weak)) = 100;

int
main(int argc, char *argv[])
{
  printf("my_var = %d\n", my_var);
}

other.c:

const int my_var = 200;

When I compile these two files and run the application, I get the following result:

my_var = 100

Since I use a weak attribute in a variable my_varin main.c, I thought it should be overridden by a variable my_varin other.c, but it wasn’t ...

Now, if I omitted the keyword const my_varin main.c:

#include <stdio.h>
/* Dropping const... */
int my_var __attribute__((weak)) = 100;

int
main(int argc, char *argv[])
{
  printf("my_var = %d\n", my_var);
}

Then recompile, we get the desired result:

my_var = 200

This is what I expect.

Note . If I omitted constthe file other.c, I still get a result of 200.

: const weak? ?

Makefile:

.PHONY: all clean

TARGET=test
OBJS=main.o other.o

all: $(TARGET)

$(TARGET): $(OBJS)
    gcc $(OBJS) -o $(TARGET)

main.o:main.c
    gcc -c main.c

other.o:other.c
    gcc -c other.c

clean:
    rm -rf *.o $(TARGET)

,

+2
1

. obsolecense ( static). , extern :

extern const int my_var;

- .

, wekref plus alias.

0

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


All Articles