MOHAMED
MOHAMED

Reputation: 43518

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?

Upvotes: 0

Views: 118

Answers (2)

Akhi
Akhi

Reputation: 190

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.

Upvotes: 2

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43508

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.

Upvotes: 5

Related Questions