const和用C弱属性++ code [英] Const and weak attribute with c++ code

查看:157
本文介绍了const和用C弱属性++ code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能够理解下面的编译错误。

I am not able to understand the compilation errors below.

第一个文件是一个标题, test_weak.h

First file is a header, test_weak.h:

#ifndef TEST_WEAK_H
#define TEST_WEAK_H
    #ifndef __ASSEMBLER__
const char* const TUTU __attribute__((weak)) ="TUTU";
const char* TUTU_DATE __attribute__((weak)) = __DATE__;
const char* const tutu ="tutu";
    #endif /*ASSEMBLER*/
#endif /*TEST_WEAK_H*/

第二个文件主要是 TEST.CPP

int main ()
{
  return 42;
}

要编译我运行: G ++ -include test_weak.h TEST.CPP -o测试

编译的结果是:

 In file included from <command-line>:0:0:
./test_weak.h:5:44: error: weak declaration of ‘TUTU’ must be public

我能够通过测试的源文件通过C扩展取代CPP推广和使用gcc代替g ++的成功运行此code。我还可以通过删除弱属性或删除第二个常量来修复这个错误。所以,是的,我能够解决的编译错误,但没有到能够在这里了解该问题的原因。

I am able to run successfully this code by replacing cpp extension by c extension on test source file and using gcc instead of g++. I am also able to fix this error by removing the weak attribute or removing the second const. So yeah I am able to fix the compilation error but no to able to understand the reason of the problem here.

例如该行编译不麻烦:

const char* TUTU __attribute__((weak)) ="TUTU";

为什么我无法使用为const char * const的 +弱使用C ++属性?

Why I cannot use a const char* const + weak attribute with c++ ?

推荐答案

属性告诉链接器如何处理多个
在不同的翻译单元同一实体的定义。
在C ++中,它是相关的,实体必须有外部
联动&MDASH;这就是连接器是指公。在C ++中,
一个变量,它本身就是常量具有内部联动
默认。你可能想要的是:

The weak attribute tells the linker how to handle multiple definitions of the same entity in different translation units. In C++, for it to be relevant, the entity must have external linkage—that's what the linker means by "public". In C++, a variable which is itself const has internal linkage by default. What you probably want is:

extern char const* const TUTU __attribute__((weak)) = "TUTU";

在形式上,这将在C未定义行为++(不
__ __属性,这是不是C ++)。弱者的目的
属性是允许它与所有的实例共享相同
内存(和它的将会的导致不确定的行为,或者至少
未指定的,如果任何实例具有不同的
初始化。

Formally, this would be undefined behavior in C++ (without the __attribute__, which isn't C++). The purpose of the weak attribute is to allow it, with all instances sharing the same memory (and it will result in undefined behavior, or at least unspecified, if any of the instances have a different initializer.

事实上:你可能想要的是:

Actually: what you probably want is:

extern char const TUTU[] __attribute__((weak)) = "TUTU";

在介绍指针没有任何点。

No point in introducing the pointer for nothing.

编辑:

请注意,这是C和C ++之间的区别之一。在
C,在常量对联动没有影响。

Note that this is one of the differences between C and C++. In C, the const has no impact on linkage.

这篇关于const和用C弱属性++ code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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