I have a question regarding weak attribute of const 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'm using weak attribute on the my_var
variable in main.c I thought it should be overridden by my_var
variable in other.c
, but that wasn't the case...
Now if I drop the const
keyword of my_var
in 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 re-compile, I get the desired result:
my_var = 200
Which is what I expect.
Note: If I drop the const
in the file other.c
I still get the result of 200.
My question is: why using const
keyword changes the behaviour of weak
attribute? Is it related to which section the variable resides in?
The Makefile I'm using is:
.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)
Thanks in advance,