GCC常数变量的弱属性 [英] GCC weak attribute on constant variables

查看:98
本文介绍了GCC常数变量的弱属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对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_varconst关键字放在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.

也许更好理解的方法是使用wekrefalias.

Maybe the better understandable approach is to use wekref plus alias.

这篇关于GCC常数变量的弱属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆