Can global auto variables be declared in h files? [duplicate]

会有一股神秘感。 提交于 2019-12-24 02:14:21

问题


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

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?


回答1:


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

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.

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;

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




回答2:


According to the C++ 17 Standard (10.1.7.4 The auto specifier)

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...

Si such a usage of the specifier auto

extern auto a;

is invalid.

You have to write

auto a = 5;

//...

extern int a;

Here is a demonstrative program

#include <iostream>

auto a = 5;

int main() 
{
    extern int a;

    std::cout << "a = " << a << '\n';
}

Take into account that it is a bad idea to define a variable in a header such a way. Starting from C++ 17 you could write

inline auto a = 5;


来源:https://stackoverflow.com/questions/57805451/can-global-auto-variables-be-declared-in-h-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!