作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在用 C 语言编写代码,其基本结构如下:
A部分:主模块的启动/初始化,各个子模块的调用以及子模块结果的最终编译。
B 部分:子模块的实际执行。
Now, part A has its own main.c and main.h file
Part B has three modules:
sub1.c/sub1.h
sub2.c/sub2.h
sub3.c/sub3.h
子模块中使用了很多公共(public)变量和函数。我想要一个通用模块,可以将其#included 包含在所有子模块中,并使用所有通用函数/变量。 (common.c 和 common.h)
现在,对于公共(public)函数,我可以在common.h中声明它们,然后在common.c中定义它们,然后它们可以直接在所有子模块中使用。但是还有很多常见的数据变量/成员我也想“通用”。
最有效的方法是什么,以便我可以直接在所有子模块中使用它们?
在 c++ 中,它可以添加到 common.h,然后可以与包含 common.h 的任何文件一起使用,但我相信它在 c 中有点不同。有人可以帮忙解释一下其中的区别吗?
谢谢
最佳答案
在 C 或 C++ 中:
应该放在.h
中:
// declaration, means it's defined somewhere else
// can declare it as many times as you want
extern int yourVariable;
每个想要使用变量需要了解它(因此在某处有一个定义)。
应该放在.c
/.cpp
中:
int yourVariable = 3; // definition, should only define it once
int yourVariable2; // also a definition
extern
关键字对于函数来说是可选的。
int square(int num); // function declaration (.h)
extern int square(int num); // same as above
int square(int num) { return num*num; } // function definition (.c)
在 C++ 中:
应该放在.h
中:
// this is a declaration
class yourClass
{
int yourVariable;
}
应该放在.cpp
中:
int yourClass::yourVariable = 3;
我可能是错的,但我不知道 C 和 C++ 在这方面的区别(除了 C++ 有类)。
关于c - 如何在c中对常见数据成员/变量进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14688281/
我是一名优秀的程序员,十分优秀!