可以在h文件中声明全局自动变量吗? [英] Can global auto variables be declared in h files?

查看:145
本文介绍了可以在h文件中声明全局自动变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有点类似于这篇文章,但仍然有所不同:我可以定义吗某些头文件中的全局auto变量?我尝试使用以下文件,但无法对其进行编译.

Somewhat similar to this post, but still different: can I define a global auto variable in some header file? I tried using the following files, but couldn't make them compile.

$ 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)之后,出现以下错误:

And after standard compilation (g++ main.cpp -o main) I got the following error:

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? Or will I have to give up this dream and find its type?

推荐答案

是否可以在源文件中定义全局自动变量并将其包含在某些头文件中?

Is there any way to define a global auto variable in the source file and include it in some header file?

您不能在不初始化的情况下声明auto变量.使用auto,从初始化程序推导类型.没有初始化程序,编译器将无法知道类型.编译器需要知道类型是什么.

You cannot declare auto variable without initialisation. With auto, the type is deduced from the initialiser. Without initialiser, the compiler cannot know the type. The compiler needs to know what the type is.

如果您改为在标头中使用推导类型,则技术上允许以下操作(根据另一个答案中链接的SO post),尽管它在很大程度上违反了使用auto的目的:

If you instead use the deduced type in the header, then following is technically allowed (according to SO post linked in the other answer) although it mostly defeats the purpose of using auto:

// header
extern int a;

// cpp
auto a = 5;

但是不幸的是,在实践中,一些编译器不喜欢这样.

But unfortunately in practice, some compilers don't like this.

作为可行的替代方案,您可以简单地使用内联变量:

As a working alternative, you could simply use an inline variable:

// header
inline auto a = 5;

C ++ 17之前的版本,您需要放弃auto对于外部变量的梦想.

Pre-C++17, you'll need to give up the dream of auto for extern variables.

这篇关于可以在h文件中声明全局自动变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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