与this post类似,但仍然不同:我可以在某些头文件中定义全局auto
变量吗?我尝试使用以下文件,但无法对其进行编译。
$ cat main.cpp
auto a = 5;
#include "defs.h"
int main(int argc, char **argv){ return a; }
$ cat defs.h
#ifndef __DEFS_H__
#define __DEFS_H__
extern auto a;
#endif
在标准编译(g++ main.cpp -o main
)之后,出现以下错误:
In file included from main.cpp:2:0:
defs.h:3:8: error: declaration of ‘auto a’ has no initializer
extern auto a;
^~~~
是否有任何方法可以在源文件中定义全局自动变量,并且 包括在一些头文件中?还是我必须放弃这个梦想并找到它的类型?
答案 0 :(得分:3)
是否可以在源文件中定义全局自动变量并将其包含在某些头文件中?
未经初始化就无法声明auto
变量。使用auto
,可以从初始化程序推导类型。没有初始化程序,编译器将无法知道类型。编译器需要知道类型是什么。
如果您改为在标头中使用推导类型,则技术上允许遵循(根据另一个答案中链接的SO post),尽管它在大多数情况下无法达到使用auto
的目的:
// header
extern int a;
// cpp
auto a = 5;
但是不幸的是,在实践中,一些编译器不喜欢这样。
作为可行的替代方案,您可以简单地使用内联变量:
// header
inline auto a = 5;
C ++ 17之前的版本,您需要放弃auto
的外部变量梦想。
答案 1 :(得分:2)
根据C ++ 17标准(10.1.7.4自动说明符)
3使用auto或decltype(auto)声明的变量的类型为 从其初始值设定项推导。 允许在初始化时使用 声明(11.6)。 ..
这样的说明符自动用法
extern auto a;
无效。
你必须写
auto a = 5;
//...
extern int a;
这是一个演示程序
#include <iostream>
auto a = 5;
int main()
{
extern int a;
std::cout << "a = " << a << '\n';
}
请注意,以这种方式在标头中定义变量不是一个好主意。从C ++ 17开始,您可以编写
inline auto a = 5;