全局外部常量说明

Van*_*yen 5 c++ constants global-variables extern

在头文件中声明 extern const 还是只是 extern 是同一件事?也都会给外部链接吗?

全局变量

#include <string>

extern const std::string foo = "bar";
Run Code Online (Sandbox Code Playgroud)

globals.h

#ifndef GLOBALS_H
#define GLOBALS_H

#include <iostream>

extern const std::string foo;

#endif  /* GLOBALS_H */
Run Code Online (Sandbox Code Playgroud)

或者

globals.h

#ifndef GLOBALS_H
#define GLOBALS_H

#include <iostream>

extern std::string foo;

#endif  /* GLOBALS_H */
Run Code Online (Sandbox Code Playgroud)

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

Naw*_*waz 5

这个是对的

//globals.h

extern const std::string foo; //Consistent
Run Code Online (Sandbox Code Playgroud)

持续的!