简体   繁体   English

C ++:在标头中声明非全局变量?

[英]C++: Declaring non-global variables in header?

In the code below, y is used in func(). 在下面的代码中,y在func()中使用。 While the code compiles, in terms of convention and/or optimization, does y need to be declared in the header file? 在按照惯例和/或优化方面编译代码时,是否需要在头文件中声明y? If so, is there anyway I can prevent y from appearing in every file that includes the header? 如果是这样,我是否可以阻止y出现在每个包含标头的文件中?

   //func.h
    #ifndef FUNC_H
    #define FUNC_H

    int func(const int x);

    #endif // FUNC_H
    //


    //func.cpp
    const int y = 5;

    int func(const int x)
    {
      return x + y;
    }
    //

No, if y is only used in func.cpp then there is no need (in terms of convention or performance) to declare it in the header file. 不,如果y仅在func.cpp中使用,则无需(从约定或性能方面)在头文件中声明它。 What you have looks fine to me. 你的东西对我来说很好。

A constant implicitly has internal linkage so it is only accessible inside func.cpp. 常量隐式具有内部链接,因此只能在func.cpp内部访问。

You could consider making it constexpr . 您可以考虑使其成为constexpr

If y is only used in func() you could consider declaring it inside func() . 如果y仅在使用func()你可以考虑宣布它里面func() I think to assume a global variable will perform better is premature optimization. 我认为假设全局变量会表现更好是过早的优化。

one option 一种选择

In the header file have the declaration 在头文件中有声明

extern const int y;

In one of the source files define the variable 在一个源文件中定义变量

const int y =5;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM