Namespaces with external linkage

前端 未结 3 1491
不知归路
不知归路 2020-12-09 23:02

The problem I have is basically the same as \'greentype\' mentions at http://www.cplusplus.com/forum/beginner/12458/

I\'m sharing variables through namespaces and a

相关标签:
3条回答
  • 2020-12-09 23:51

    This has nothing really to do with namespaces, and all to do with the linkage, external or otherwise of the symbol i in your various examples. By default, global variables have extern linkage, while global const symbols have static linkage - this explains why it works when you make i const. To resolve your problem, one way is to declare i with extern linkage in the header file, then define it in only one of the implementation files, as shown below:

    header:

    extern int i;
    

    a.c:

    int i:
    

    main.c:

    int main()
    {
      i = 1; // or whatever
    }
    

    Note that I have removed the namespace for clarity - the end result is the same.

    0 讨论(0)
  • 2020-12-09 23:54

    Any global object, like i, must have exactly one definition somewhere in the program, but it can be declared multiple times.

    Using extern without an initializer makes a declaration just a declaration. This is appropriate for your header file, but you must still define i somewhere. As well as making the header declaration extern you also need to add a definition (i.e. a copy of the declaration without extern) to one and only one of your source files.

    Edit: Reading your question, you say that you want to pass a variable to a function. From a style and code structure point of view, this isn't usually a good reason for using a shared (global) variable. In the absence of any overriding reasons you should normally define a function which takes a parameter and pass a value (possibly from a local variable) from the calling site to that function via its parameter.

    0 讨论(0)
  • 2020-12-09 23:54

    The header file should say:

    namespace nn {
        extern int i;
    }
    

    This is a "declaration" not a "definition". You then want a definition in one and only one file:

    namespace nn {
        int i = 1;
    }
    

    Of course, a much better approach is just to not have globals at all.

    0 讨论(0)
提交回复
热议问题