【问题标题】:C and global variables/functionsC 和全局变量/函数
【发布时间】:2012-08-30 06:30:14
【问题描述】:

我正在移植我拥有的一些 C++ 代码。它在 C++ 中完美运行,所以我不知道我做错了什么。 我有“a.c”和“b.c”。它们都包括“a.h”,而后者又包括“b.h”。 "b.c" 中的函数在其头文件中声明(使用extern 关键字),其中之一是从"a.c" 调用的。它编译并运行,但调用似乎从未通过(我什至在其中添加了几行 printf() 进行诊断,但没有任何反应)。

我知道我忽略了一些简单的事情,我就是无法确定是什么。任何帮助表示赞赏。

编辑:粘贴一些简化代码: 编辑 2:通话通过,有一个库问题需要修复。现在索引变量没有增加,我认为这可能是一个范围问题。

在“交流”中

    #include "a.h"
    ...
    int sSimDisp(void){
        buttons();
    printf("x = %04d\n", index);
        ...
    }
    int main(){
    ...
    while(1) {
        sSimDisp();
        ...
    }
    return 0;
    }

在“啊.h”中

    #ifndef a_H_
    #define a_H_
    ...
    #include "b.h"
    #include "c.h"
    int sSimDisp(void);
    int main(void);
    #endif /* a_H_ */

在“b.c”中

    #include "a.h"
    ...
    int index = 0;
    void buttons(){
      printf("Entry to button subroutine.\n");
        index++;
        ...
    }
    void touchscreen(){
    ...
    }

在“b.h”中

    #ifndef b_H_
    #define b_H_
    ...
    extern int index;
    //button handler
    void buttons();
    //touch screen handler
    void touchscreen();   
    #endif /* b_H_ */

【问题讨论】:

  • 您的printf 通话结束时是否有'\n'
  • "带 extern 关键字" - 所有函数默认为extern
  • 你能做一个最小的例子给我们看吗?参见例如sscce.org
  • 我会精简代码并粘贴它。我只在变量上使用了“extern”,这是我发帖时的错误。
  • 尝试在调试器中运行它,并单步执行代码以查看它的作用。

标签: c header global extern


【解决方案1】:

您在 a.h 中声明 int main(void) 很可能会导致未定义的行为。

程序中只能有一个main,并且你不要在header中放置原型。

【讨论】:

  • 您能用参考资料备份此声明吗?我无法想象额外的、一致的 main 声明会造成多大的伤害。
  • 来自(我认为是 C++)标准文档,3.6.1.2 主函数,它的返回类型应为 int 类型,否则它的类型是实现定义的。所有实现都应允许以下两种 main 定义: int main() { / ... / } 和 int main(int argc, char* argv[]) { / ... / } 它没有说明是否允许允许声明。
【解决方案2】:

我的代码没有问题,这些库真的被抬高了。我要抓住这些家伙,我们将整理对 repo 的最后更改。感谢您的帮助,我只是想确保我没有做错任何事情。

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    相关资源
    最近更新 更多