如何在C中访问正确的全局变量?

时间:2022-09-06 13:51:58

lets say I have some global var GLOBAL in main.c, but my main.c has a #include "other.h". But other.h has global var GLOBAL too.

假设我有一些全局变量。c,但我的主要。c有一个#include "other.h"。但是其他的。h也具有全局var。

How do I let the compiler know which one I meant when I write GLOBAL in main. Is there a "this" keyword that I can use?

如何让编译器知道我在主程序中写全局变量时的意思。我可以使用“this”关键词吗?

7 个解决方案

#1


-1  

I'm assuming you've defined the variable in the program, and not in the preprocessor using a #define.

我假设您已经在程序中定义了变量,而不是在使用#define的预处理器中。

If you want to refer to the one created in the main.c, you just type global. To refer to those in your header file, use the keyword extern.

如果您想要引用在main中创建的。c,输入全局变量。要引用头文件中的内容,请使用关键字extern。

You'd be better declaring them as two seperate variable names though to be honest.

您最好将它们声明为两个独立变量名,但要诚实。

#2


10  

You can't have two global variables with the same name in C program. C might allow multiple definitions in the same file scope through the tentative definition rule, but in any case all definitions will refer to the same variable. So, apparently your question is based on incorrect premise. There's no issue of "which one" here. You only have one variable.

在C程序中不能有两个名称相同的全局变量。C可以通过暂定定义规则在同一文件范围内允许多个定义,但是在任何情况下,所有定义都将引用相同的变量。显然,你的问题是基于错误的前提。这里没有“哪个”的问题。你只有一个变量。

For example, you can have a sequence of file-scope definitions in C translation unit

例如,您可以在C转换单元中拥有一系列文件范围定义

int i;
int i;
int i;

This is legal in C (as opposed to C++) and all these definitions are actually defining the same variable, not three different variables.

这在C中是合法的(与c++相反),所有这些定义实际上都定义了相同的变量,而不是三个不同的变量。

Of course, if one of the variables is defined as a local variable (if so, you have to state it in your question) (BTW, why is it called GLOBAL then?), then it will hide the name of the variable defined in the file scope (or any higher scope). In this case there's no way to access the hidden name in C. Rename the local variable to avoid hiding the global one.

当然,如果其中一个变量被定义为局部变量(如果是,您必须在您的问题中声明它)(顺便说一句,为什么它被称为全局变量?),那么它将隐藏在文件范围(或任何更高的范围)中定义的变量的名称。在这种情况下,无法访问c中的隐藏名,重新命名本地变量以避免隐藏全局变量。

What you mean by "other.h also has the variable" is not clear as well. What does "has" mean in this case? Is the variable defined in other.h? Or just declared? If it is just declared, then it doesn't really "have" it. If it is defined there... well, then the real question is: why are you defining variables in .h files?

你说的“其他”是什么意思?h也有变量"也不清楚。在这种情况下,have是什么意思?变量是否在其他。h中定义?或者只是宣布?如果它刚刚声明,那么它并没有真正“拥有”它。如果它在那里被定义……那么,真正的问题是:为什么要在.h文件中定义变量?

#3


5  

You don't actually have two variables. There is only one, you will either get a compiler (or linker) error if two modules declare the same global with the same name, or the compiler/linker will decide that you meant this to be redundant declarations of a single variable and merge them.

实际上没有两个变量。只有一个,如果两个模块用相同的名称声明相同的全局变量,那么您将得到一个编译器(或链接器)错误,或者编译器/链接器将决定您的意思是这是单个变量的冗余声明并合并它们。

#4


2  

Like others have mentioned, avoid using the same global variable/function names. Take the habit of prefixing them with the module name. I.e. MODULE1_state, MODULE2_state, etc.

像其他人提到的,避免使用相同的全局变量/函数名。习惯使用模块名对它们进行前缀。例如MODULE1_state,MODULE2_state等等。

If a global variable is only going to be used inside one source file, don't declare it in the matching header file. Instead, declare it at the top of the source file, and use the static keyword. Variables that need to be accessible to other modules need to be declared in the header file using the extern keyword. The same applies to global functions. It helps to maintain the same public/private discipline you'd normally use in an object-oriented language like C++, Java, C#, etc.

如果一个全局变量只在一个源文件中使用,不要在匹配的头文件中声明它。相反,在源文件的顶部声明它,并使用static关键字。其他模块需要访问的变量需要在头文件中使用extern关键字声明。这同样适用于全局函数。它有助于维护您通常在面向对象语言中使用的公共/私有规则,如c++、Java、c#等。

Example:

例子:

In module.h:

在module.h:

#ifndef MODULE_H /* Header guard */
#define MODULE_H

/* Declarations for entities that CAN be accessed by other modules,
   i.e. "public". */
extern int MOD_publicVariable;
extern void MOD_publicFunction(int arg);

#endif // MODULE_H

In module.c:

在module.c:

/* Definitions for entities that CAN be accessed by other modules,
   i.e. "public". */
int MOD_publicVariable = 42;
void MOD_publicFunction(int arg) {...}

/* Declarations for entities that CAN'T be accessed by other modules,
   i.e. "private". */
static double MOD_privateVariable = 12.34;
static void MOD_privateFunction1(void);
static void MOD_privateFunction2(void);

/* Function definitions. */
void MOD_privateFunction1(void) {
     int localVariable; /* This doesn't need the module prefix. */
     ....
}

void MOD_privateFunction2(void) {
     ....
}

The module prefix (MOD_) can be named directly after your module, or you can use an abbreviation. Experiment, and you'll eventually settle on a convention you like. Consistently using a prefix like this emulates the concept of a class/module/namespace in OO languages.

模块前缀(MOD_)可以直接以模块命名,也可以使用缩写。做实验,你最终会选择一个你喜欢的习惯。始终如一地使用这样的前缀,可以模拟OO语言中类/模块/名称空间的概念。

Make sure you know the difference between declaration vs. definition, and extern vs. static.

确保你知道声明和定义,外部和静态之间的区别。

It irks me that C textbooks and courses either ignore or gloss over the art of multi-module programming.

我讨厌C教科书和课程忽视或掩盖了多模块编程的艺术。

EDIT: I forgot to mention that you should not generally make global variables accessible to other modules (i.e. make them "private"). If other modules need to access that variable, provide "public" "setter" and/or "getter" functions.

编辑:我忘了说,通常不应该让全局变量对其他模块(例如,让它们“私有”)可访问。如果其他模块需要访问该变量,请提供“public”“setter”和/或“getter”函数。

#5


0  

You can have only one definition per object module. The second one, if has the same content, will be ignored. If it differs, it will result in compiler error.

每个对象模块只能有一个定义。第二个,如果有相同的内容,将被忽略。如果它不同,将导致编译器错误。

#6


0  

This might not be the answer you are looking for, but why don't you try to avoid this kind of situations in the first place (and potentially the (over)use of globals)?

这可能不是你想要的答案,但是你为什么不试着在一开始就避免这种情况(并且潜在地使用全局变量)呢?

#7


0  

First off, if this is an issue in the first place, you're using a crappy library and should rewrite/switch if possible. If you can't, you can do something like this:

首先,如果这首先是一个问题,那么您正在使用一个糟糕的库,如果可能的话应该重写/切换。如果你做不到,你可以这样做:

other.h:

other.h:

int GLOBAL;
//...other stuff

main.c

c

int GLOBAL;
#define GLOBAL OTHER_GLOBAL
#include "other.h"
#undef GLOBAL

int main(int argc,char** argv)
    {
    printf("%i %i",GLOBAL,OTHER_GLOBAL);
    getchar();
    return 0;
    }

however, if as the capitals imply, GLOBAL is #defineed, this might not work. (But it's worth a try anyway.)

然而,如果像大写字母所暗示的那样,GLOBAL是#defineed,这可能行不通。(但无论如何,这值得一试。)

#1


-1  

I'm assuming you've defined the variable in the program, and not in the preprocessor using a #define.

我假设您已经在程序中定义了变量,而不是在使用#define的预处理器中。

If you want to refer to the one created in the main.c, you just type global. To refer to those in your header file, use the keyword extern.

如果您想要引用在main中创建的。c,输入全局变量。要引用头文件中的内容,请使用关键字extern。

You'd be better declaring them as two seperate variable names though to be honest.

您最好将它们声明为两个独立变量名,但要诚实。

#2


10  

You can't have two global variables with the same name in C program. C might allow multiple definitions in the same file scope through the tentative definition rule, but in any case all definitions will refer to the same variable. So, apparently your question is based on incorrect premise. There's no issue of "which one" here. You only have one variable.

在C程序中不能有两个名称相同的全局变量。C可以通过暂定定义规则在同一文件范围内允许多个定义,但是在任何情况下,所有定义都将引用相同的变量。显然,你的问题是基于错误的前提。这里没有“哪个”的问题。你只有一个变量。

For example, you can have a sequence of file-scope definitions in C translation unit

例如,您可以在C转换单元中拥有一系列文件范围定义

int i;
int i;
int i;

This is legal in C (as opposed to C++) and all these definitions are actually defining the same variable, not three different variables.

这在C中是合法的(与c++相反),所有这些定义实际上都定义了相同的变量,而不是三个不同的变量。

Of course, if one of the variables is defined as a local variable (if so, you have to state it in your question) (BTW, why is it called GLOBAL then?), then it will hide the name of the variable defined in the file scope (or any higher scope). In this case there's no way to access the hidden name in C. Rename the local variable to avoid hiding the global one.

当然,如果其中一个变量被定义为局部变量(如果是,您必须在您的问题中声明它)(顺便说一句,为什么它被称为全局变量?),那么它将隐藏在文件范围(或任何更高的范围)中定义的变量的名称。在这种情况下,无法访问c中的隐藏名,重新命名本地变量以避免隐藏全局变量。

What you mean by "other.h also has the variable" is not clear as well. What does "has" mean in this case? Is the variable defined in other.h? Or just declared? If it is just declared, then it doesn't really "have" it. If it is defined there... well, then the real question is: why are you defining variables in .h files?

你说的“其他”是什么意思?h也有变量"也不清楚。在这种情况下,have是什么意思?变量是否在其他。h中定义?或者只是宣布?如果它刚刚声明,那么它并没有真正“拥有”它。如果它在那里被定义……那么,真正的问题是:为什么要在.h文件中定义变量?

#3


5  

You don't actually have two variables. There is only one, you will either get a compiler (or linker) error if two modules declare the same global with the same name, or the compiler/linker will decide that you meant this to be redundant declarations of a single variable and merge them.

实际上没有两个变量。只有一个,如果两个模块用相同的名称声明相同的全局变量,那么您将得到一个编译器(或链接器)错误,或者编译器/链接器将决定您的意思是这是单个变量的冗余声明并合并它们。

#4


2  

Like others have mentioned, avoid using the same global variable/function names. Take the habit of prefixing them with the module name. I.e. MODULE1_state, MODULE2_state, etc.

像其他人提到的,避免使用相同的全局变量/函数名。习惯使用模块名对它们进行前缀。例如MODULE1_state,MODULE2_state等等。

If a global variable is only going to be used inside one source file, don't declare it in the matching header file. Instead, declare it at the top of the source file, and use the static keyword. Variables that need to be accessible to other modules need to be declared in the header file using the extern keyword. The same applies to global functions. It helps to maintain the same public/private discipline you'd normally use in an object-oriented language like C++, Java, C#, etc.

如果一个全局变量只在一个源文件中使用,不要在匹配的头文件中声明它。相反,在源文件的顶部声明它,并使用static关键字。其他模块需要访问的变量需要在头文件中使用extern关键字声明。这同样适用于全局函数。它有助于维护您通常在面向对象语言中使用的公共/私有规则,如c++、Java、c#等。

Example:

例子:

In module.h:

在module.h:

#ifndef MODULE_H /* Header guard */
#define MODULE_H

/* Declarations for entities that CAN be accessed by other modules,
   i.e. "public". */
extern int MOD_publicVariable;
extern void MOD_publicFunction(int arg);

#endif // MODULE_H

In module.c:

在module.c:

/* Definitions for entities that CAN be accessed by other modules,
   i.e. "public". */
int MOD_publicVariable = 42;
void MOD_publicFunction(int arg) {...}

/* Declarations for entities that CAN'T be accessed by other modules,
   i.e. "private". */
static double MOD_privateVariable = 12.34;
static void MOD_privateFunction1(void);
static void MOD_privateFunction2(void);

/* Function definitions. */
void MOD_privateFunction1(void) {
     int localVariable; /* This doesn't need the module prefix. */
     ....
}

void MOD_privateFunction2(void) {
     ....
}

The module prefix (MOD_) can be named directly after your module, or you can use an abbreviation. Experiment, and you'll eventually settle on a convention you like. Consistently using a prefix like this emulates the concept of a class/module/namespace in OO languages.

模块前缀(MOD_)可以直接以模块命名,也可以使用缩写。做实验,你最终会选择一个你喜欢的习惯。始终如一地使用这样的前缀,可以模拟OO语言中类/模块/名称空间的概念。

Make sure you know the difference between declaration vs. definition, and extern vs. static.

确保你知道声明和定义,外部和静态之间的区别。

It irks me that C textbooks and courses either ignore or gloss over the art of multi-module programming.

我讨厌C教科书和课程忽视或掩盖了多模块编程的艺术。

EDIT: I forgot to mention that you should not generally make global variables accessible to other modules (i.e. make them "private"). If other modules need to access that variable, provide "public" "setter" and/or "getter" functions.

编辑:我忘了说,通常不应该让全局变量对其他模块(例如,让它们“私有”)可访问。如果其他模块需要访问该变量,请提供“public”“setter”和/或“getter”函数。

#5


0  

You can have only one definition per object module. The second one, if has the same content, will be ignored. If it differs, it will result in compiler error.

每个对象模块只能有一个定义。第二个,如果有相同的内容,将被忽略。如果它不同,将导致编译器错误。

#6


0  

This might not be the answer you are looking for, but why don't you try to avoid this kind of situations in the first place (and potentially the (over)use of globals)?

这可能不是你想要的答案,但是你为什么不试着在一开始就避免这种情况(并且潜在地使用全局变量)呢?

#7


0  

First off, if this is an issue in the first place, you're using a crappy library and should rewrite/switch if possible. If you can't, you can do something like this:

首先,如果这首先是一个问题,那么您正在使用一个糟糕的库,如果可能的话应该重写/切换。如果你做不到,你可以这样做:

other.h:

other.h:

int GLOBAL;
//...other stuff

main.c

c

int GLOBAL;
#define GLOBAL OTHER_GLOBAL
#include "other.h"
#undef GLOBAL

int main(int argc,char** argv)
    {
    printf("%i %i",GLOBAL,OTHER_GLOBAL);
    getchar();
    return 0;
    }

however, if as the capitals imply, GLOBAL is #defineed, this might not work. (But it's worth a try anyway.)

然而,如果像大写字母所暗示的那样,GLOBAL是#defineed,这可能行不通。(但无论如何,这值得一试。)