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? i.e.:
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, i.e. 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?
Actually, no. There is no more clear and efficient way.
However, there are some options available:
.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.-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:
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.