简体   繁体   中英

No build error when including header file (containing variable definition) in 2 c files

I have a header file h1.h containing the following variable declaration:

h1.h

struct namespaces
{
    char *soap_env;
    char *soap_enc;
    char *xsd;
    char *xsi;
} ns;

I included the header file h1.h in 2 C files c1.c and c2.c .

c1.c

#include "h1.h"

c2.c

#include "h1.h"

I expect to get an error in the build, but I did not. There is no error and no warnings in the In the build.

Is it normal?

Does a such issue cause an undefined behaviour when the program is running?

Each C source file gets processed by the compiler separately, so you don't have to worry that the same header file is included by two different source files.

A problem would occur if you attempt to include the same header file within a single source file. That is why having include guards in header files (pragmas or #ifndef ... ) is a widely adopted idiom in C programming.

Another problem that will happen is that both c1.c and c2.c will get their own ns. So if one modifies it, other will not see the modifications. Generally speaking, that is not what one wants.

The convention is to define ns in one c file, put it as an extern in the header file and be able to use it in other c files.

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