简体   繁体   中英

Share type across multiple source files - C

I'm relatively new to C and learning as I go. One thing I'm having a hard time with is sharing data across multiple files. I've got the use of extern down with simple things such as character arrays and integers. But what of an instance when it comes to a type, such as using MySQL? ie:

main.c:

#include <mysql.h>
#include <my_global.h>
MYSQL *mysql_con;

main.h:

#include <mysql.h>
#include <my_global.h>

extern MYSQL *mysql_con;

I am able to use mysql_con via other files - so long as I include the mysql.h and my_global.h IN those other files, headers included (if I don't put the include in the header files for other files, ie functions.h and functions.c, it gawks at compile time due to unknown types when I make the function prototype).

My question is: is there a way around having to include the same headers over and over and over again in anything and everything that's going to use mysql_con ? I even had to include the headers for mysql in the main.h just to declare the extern! Is there are more efficient way of doing this?

No. This is probably one of those cases where the issue you're having isn't really your problem. You don't want to share a global variable amongst your files, but rather explicitly pass the connection to the functions that need it.

This gives you greater control of the connection's scope. Instead of any function being able to mutate mysql_con , only functions that you define would be able to.

I once worked with a gentleman who had a file named database.h where he kept every single variable in; needless to say his code had a lot of bugs and issues.

Actually, no. There is no more clear and efficient way.

However, there are some options available:

  1. Write content of your header file in your .c file. You may just write extern MYSQL *mysql_con; in your .c file every time you want to use it. That is more typing and may introduce more errors. Don't do this .
  2. You may include your header file with compiler. -include my_header.h option does that. If you have one command to build all your source files, that is less typing. However, I don't recommend that, too. There are two reasons:
    • Nobody expects this. People usually don't look at your build scripts.
    • You don't want this header file to be included in all your source files.

I recommend including header file every single time. With good text editor that is not much overhead.

By the way, many other languages also follow this way. You should import in Java and Python. Pascal uses uses . So everyone thinks it's ok.

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