简体   繁体   中英

What is the correct way to include nested header files in multithreading in 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

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

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.

So:

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

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

Do follow these rules:

  1. Do not define variables in headers, only declare them. Ie always use extern with variables.
  2. Define each variable (declared extern by 1.) exactly once in exactly one code file, ie 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; ie with ; at the end.
  5. Function definitions go into code files, once; ie 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.).

Example of a reinclusion guard:

MyHeader.h:

#ifndef MYHEADER_H
#define MYHEADER_H

/* only declarations */

#endif /* MYHEADER_H */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM