GCC常数变量的弱属性 [英] GCC weak attribute on constant variables
问题描述
我对const变量的弱属性有疑问.我有以下几个用gcc编译的文件:
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
因为我在main.c中的my_var
变量上使用了弱属性,所以我认为应该由other.c
中的my_var
变量覆盖它,但事实并非如此...
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...
现在,如果我将my_var
的const
关键字放在main.c
中:
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
我期望的是什么.
注意:如果将const
放到文件other.c
中,我仍然得到200的结果.
Note: If I drop the const
in the file other.c
I still get the result of 200.
我的问题是:为什么使用const
关键字会更改weak
属性的行为?它与变量所在的部分有关吗?
My question is: why using const
keyword changes the behaviour of weak
attribute? Is it related to which section the variable resides in?
我正在使用的Makefile是:
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)
预先感谢
推荐答案
标识符具有内部链接.这是一个过时的功能(应使用static
存储类说明符).通常,您应该在标头中包含标识符的extern
声明:
The identifiers have internal linkage. This is an obsolecense feature (static
storage class specifier should be used). In general, you should have a header with an extern
declaration of the identifier:
extern const int my_var;
链接不同的限定词是一个坏主意.
Linking with different qualifiers is a bad idea.
也许更好理解的方法是使用wekref
加alias
.
Maybe the better understandable approach is to use wekref
plus alias
.
这篇关于GCC常数变量的弱属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!