Search code examples
c++global-variablesheader-filesauto

Can global auto variables be declared in h files?


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?


Solution

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