全局自动变量可以在h文件中声明吗?
Can global auto variables be declared in h files?
有点类似于,但仍然不同:我可以在一些头文件中定义一个全局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;
^~~~
有什么办法可以在源文件中定义一个全局自动变量并且
将它包含在一些头文件中?还是我必须放弃这个梦想并找到它的类型?
Is there any way to define a global auto variable in the source file and include it in some header file?
你不能在没有初始化的情况下声明 auto
变量。使用 auto
,类型是从初始化程序中推导出来的。没有初始化器,编译器无法知道类型。编译器需要知道类型是什么。
如果您改为在 header 中使用推导类型,那么技术上允许使用以下内容(根据另一个答案中链接的 SO post),尽管它主要违背了使用 auto
:
// header
extern int a;
// cpp
auto a = 5;
但不幸的是,在实践中,一些编译器不喜欢这样。
作为一种可行的替代方法,您可以简单地使用一个内联变量:
// header
inline auto a = 5;
Pre-C++17,你需要放弃对外部变量的auto
梦想。
根据 C++ 17 标准(10.1.7.4 自动说明符)
3 The type of a variable declared using auto or decltype(auto) is
deduced from its initializer. This use is allowed in an initializing
declaration (11.6) of a variable...
说明符 auto 的这种用法
extern auto a;
无效。
你必须写
auto a = 5;
//...
extern int a;
这是一个演示程序
#include <iostream>
auto a = 5;
int main()
{
extern int a;
std::cout << "a = " << a << '\n';
}
请注意,以 header 的方式定义变量不是一个好主意。从 C++ 17 开始,您可以编写
inline auto a = 5;
有点类似于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;
^~~~
有什么办法可以在源文件中定义一个全局自动变量并且 将它包含在一些头文件中?还是我必须放弃这个梦想并找到它的类型?
Is there any way to define a global auto variable in the source file and include it in some header file?
你不能在没有初始化的情况下声明 auto
变量。使用 auto
,类型是从初始化程序中推导出来的。没有初始化器,编译器无法知道类型。编译器需要知道类型是什么。
如果您改为在 header 中使用推导类型,那么技术上允许使用以下内容(根据另一个答案中链接的 SO post),尽管它主要违背了使用 auto
:
// header
extern int a;
// cpp
auto a = 5;
但不幸的是,在实践中,一些编译器不喜欢这样。
作为一种可行的替代方法,您可以简单地使用一个内联变量:
// header
inline auto a = 5;
Pre-C++17,你需要放弃对外部变量的auto
梦想。
根据 C++ 17 标准(10.1.7.4 自动说明符)
3 The type of a variable declared using auto or decltype(auto) is deduced from its initializer. This use is allowed in an initializing declaration (11.6) of a variable...
说明符 auto 的这种用法
extern auto a;
无效。
你必须写
auto a = 5;
//...
extern int a;
这是一个演示程序
#include <iostream>
auto a = 5;
int main()
{
extern int a;
std::cout << "a = " << a << '\n';
}
请注意,以 header 的方式定义变量不是一个好主意。从 C++ 17 开始,您可以编写
inline auto a = 5;