在c中的多线程中包含嵌套头文件的正确方法是什么 [英] What is the correct way to include nested header files in multithreading in c

查看:23
本文介绍了在c中的多线程中包含嵌套头文件的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下头文件和源文件.

I have the following header and source files.

clnt_thread.h        included in clnt_thread.cpp and main.c
jacc_sim.h           included in jacc_sim.cpp and main.c
srvr_info.h          included in srvr_info.cpp and main.c
constants.h          included in clnt_thread.h and in srvr_info.h, both see above
                          and in global_variables.c
global_variables.h   included in main.c
main.c

一些变量在 clnt_thread.h 中声明为 extern,而在 jacc_sim.h 中声明为其他变量.

Some variables are declared as extern in clnt_thread.h and others in jacc_sim.h.

我的问题是,当我在某些头文件中将全局变量定义为 extern 时,我收到错误提示它们未定义或已定义多次.另外,一些全局变量将在线程之间共享,而一些全局变量将由每个线程独立使用.

My problem is, when I define the global variables as extern in some of the header files I get errors saying that either they are undefined or they are defined multiple times. Plus, some of the global variables are to be shared among threads while some are to be used by each thread independently.

我知道这些错误是由于头文件嵌套(包含)在源文件中的方式造成的.

I know these errors are a result of the way the header files are nested(included) in the source files.

所以:

  1. 包含这些头文件并定义extern变量的正确方法是什么?

  1. What is the correct way to include these header files and define the extern variables?

如何区分线程间共享的变量和不应在线程间共享的变量?

What distinguishes a variable shared among threads and another one which should not be shared between threads?

推荐答案

请遵守以下规则:

  1. 不要在头文件中定义变量,只声明它们.IE.始终将 extern 与变量一起使用.
  2. 在一个代码文件中定义每个变量(用 1 声明的 extern.)恰好一次,即不使用 extern.
  3. 即使声明变量也只能在一个标头中进行一次.(尽管如果您始终如一地执行此操作,编译器不会抱怨,但只执行一次仍然更清洁、更安全.)
  4. 函数原型进入标题,一次;即以 ; 结尾.
  5. 函数定义一次进入代码文件;即带有函数头(没有 ; 的原型),后跟函数体({...}).
  6. 无论您想访问或引用什么,都将声明它的标头包含在文件中(您需要它的标头或代码文件).
  7. 使用重新包含保护以提高安全性(主要用于宏等).
  1. Do not define variables in headers, only declare them. I.e. always use extern with variables.
  2. Define each variable (declared extern by 1.) exactly once in exactly one code file, i.e. without extern.
  3. Even declaring variables should only be done once, in one header. (Though the compiler will not complain if you do it consistently, it is still much cleaner and safer to do it only once.)
  4. Function prototypes go into headers, once; i.e. with ; at the end.
  5. Function definitions go into code files, once; i.e. with function head (prototype without ;) followed by function body ( {...}).
  6. Whatever you want to access or refer to, include the header which declares it into the file (header or code file you need it in).
  7. Use reinclusion guards for extra safety (mostly for macros etc.).

重新包含保护的示例:

MyHeader.h:

MyHeader.h:

#ifndef MYHEADER_H
#define MYHEADER_H

/* only declarations */

#endif /* MYHEADER_H */

这篇关于在c中的多线程中包含嵌套头文件的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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