c - 如何在c中对常见数据成员/变量进行分组?

标签 c header include

我正在用 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/

相关文章:

c - 从远程过程调用返回字符串

c++ - 使用混合 C 和 C++ 对函数的 undefined reference

header - 如何添加 Access-Control-Allow-Origin header

c++ - 在使用数学函数时在 openCl 和设备中使用函数

include - 交响乐 4 : Multiple inclusion of a file

c - 在纯 C 中打开一个 Unicode 文件

c++ - c/c++预处理器: how to ensure that correct file is included

php - 在 PHP header 重定向中传递电子邮件 - 删除 "@"?

编译器找不到 sstream?

c - 理解 C 中的格式说明符