可变重定义,嵌入式c [英] variable redefinition, embedded c

查看:165
本文介绍了可变重定义,嵌入式c的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从事一个嵌入式的c项目,并且有全局变量重新定义的问题。



我把函数声明和定义分成几个.h和.c文件。许多这些功能需要访问global_vars.h中定义的全局变量。因此,在头文件的开头,#ifndef,#define部分,global_vars.h中。如果我没有,你可能会想到我会收到一堆未定义的变量错误。



然而,尽管global_vars.h具有#ifndef _GLOBAL_VARS_H_ #define .. #endif,我得到所有全局变量的重新定义错误。我的猜测是,当链接器尝试链接各种对象文件时,会看到所有blah_blah.h文件中的#includeglobal_vars.h的重新定义。这是我的理解,但是,#ifndef ...关心这个问题。



有没有什么我忽略?



提前感谢

解决方案

链接器从未在global_vars.h文件中看到任何内容,除非 - 坏消息! - 某些全局变量实际上是 定义 。 global_vars.h应该仅保留这些全局变量的 声明 ,从不(甚至几乎从不)他们的定义。



在global_vars.h中,您应该有以下声明:

  extern int some_global; 

您不能拥有:

  int some_global; 

如果在global_vars.h中有定义,那么是的,它们将在链接时被乘法定义因为#include global_vars.h中的每个.c文件将有自己定义的每个定义的变量。



的所有定义extern 全局必须在某些 .c文件中。通常这个.c文件无关紧要。通常,所有全局变量定义都在一个名为(惊喜!)global_vars.c的文件中。



因此,请确保global_vars中没有任何全局变量定义.h,你会很好。


I'm working on an embedded c project and am having issues with global variable redefinition.

I've split up the function declarations and definitions into a handful of .h and .c files. Many of these functions need access to global variables, which are defined in global_vars.h. Therefore, at the beginning of the header files, inside the #ifndef, #define section, "global_vars.h". If I don't, as you might imagine I get a bunch of undefined variable errors.

However, even though global_vars.h has the #ifndef _GLOBAL_VARS_H_ #define... #endif, I get redefinition errors for all the global variables. My guess is that when the linker tries link the various object files, it sees the redefinition due to the #include "global_vars.h" in all the "blah_blah.h" files. It was my understanding, though, that the #ifndef... takes care of this issue.

Is there something I'm overlooking?

Thanks in advance

解决方案

The linker never sees anything in the global_vars.h file, ever, unless -- bad news! -- some of the globals are actually defined in that file. global_vars.h should hold only declarations of those global variables, never (well, almost never) their definitions.

In global_vars.h, you should have declarations like:

extern int some_global;

You are not allowed to have:

int some_global;

If you have definitions in global_vars.h then, yes, they'll be multiply defined at link time because each of the .c files that #includes global_vars.h will have its own definition of each defined variable.

All of the definitions of the extern globals must be in some .c file, for sure. Usually it doesn't matter which .c file. Often all of the global-variable definitions are in a file called (surprise!) global_vars.c.

So make sure there aren't any global-variable definitions in global_vars.h and you'll be in good shape.

这篇关于可变重定义,嵌入式c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆