c++ - 全局外部常量说明

标签 c++ global-variables constants extern

在头文件中声明 extern const 或仅仅声明 extern 是一样的吗?也都会给外部链接吗?

全局变量

#include <string>

extern const std::string foo = "bar";

全局变量

#ifndef GLOBALS_H
#define GLOBALS_H

#include <iostream>

extern const std::string foo;

#endif  /* GLOBALS_H */

全局变量

#ifndef GLOBALS_H
#define GLOBALS_H

#include <iostream>

extern std::string foo;

#endif  /* GLOBALS_H */

两者都编译和运行良好,在多个文件中使用时都给出相同的地址,哪个更正确?

最佳答案

这个是对的,

//globals.h

extern const std::string foo; //Consistent

一致!

关于c++ - 全局外部常量说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4547147/

相关文章:

c++ -::运算符能否出现在与限定名称查找中的范围解析不同的上下文中?

c++ - 如何访问类内部类的对象?

Java 到 Cpp 代码转换 : compareTo

c++ - 全局变量的线程和函数调用安全

c - 将大型 const 结构传递给函数

c++ - const 函数最终通过友元类修改自身

c++ - unicode char 或 multibyte char :which type is more efficient? 为什么?

Python:日志记录模块 - 全局

c - 动态分配的函数中的局部指针变量会发生什么?

c++ - 带有 const 模板参数的模板模板类