简体   繁体   English

在同一个 header 文件中声明、初始化和使用全局变量

[英]Declaring,initializing and using a global variable in same header file

I am actually trying to use a variable that is initialized in a header file(say xh) and want to use same variable inside inlined code in the same header file.我实际上是在尝试使用在 header 文件(比如 xh)中初始化的变量,并希望在同一个 header 文件的内联代码中使用相同的变量。 The same variable is modified in another file (say yc).在另一个文件(比如 yc)中修改了相同的变量。 How can i do this?我怎样才能做到这一点? I would like to know a good way of doing this.我想知道这样做的好方法。

Using the extern reserved word.使用extern保留字。

Never create variables in '.h' files, it's a bad practice that leads to bugs.永远不要在 '.h' 文件中创建变量,这是一种不好的做法,会导致错误。 Instead, declare them as extern everywhere you need to use them and declare the variable itself only in a single '.c' file where it will be instantiated, and linked to from all the other places you use it.相反,在您需要使用它们的任何地方将它们声明为extern ,并仅在单个“.c”文件中声明变量本身,该文件将被实例化,并从您使用它的所有其他地方链接到。

You can declare the global variable in the header file as extern , and then define it inside a code-module (ie, ".c" file).您可以将 header 文件中的全局变量声明为extern ,然后在代码模块(即“.c”文件)中定义它。 That way you won't end up with multiple definition errors thrown by the linker.这样您就不会遇到 linker 引发的多个定义错误。

So for example in your header file, a globally available int named my_global_var would have a declaration in ah file that looks like:因此,例如在您的 header 文件中,名为my_global_var的全局可用int将在 ah 文件中具有如下声明:

extern int my_global_var;

Then inside a single.c file somewhere you would define and initialize it:然后在一个单一的.c 文件中,您可以定义和初始化它:

int my_global_var = 0;

Now you can use my_global_var in any other code module that includes the appropriate header file and links with the proper.c file containing the definition of the global variable.现在您可以在任何其他代码模块中使用my_global_var ,该代码模块包括相应的 header 文件并与包含全局变量定义的正确 c 文件链接。

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

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