简体   繁体   English

在2个c文件中包含头文件(包含变量定义)时,没有构建错误

[英]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其中包含以下变量声明:

h1.h 1小时

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 . 我将头文件h1.h包含在2个C文件c1.cc2.c

c1.c c1.c

#include "h1.h"

c2.c 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. 每个C源文件都由编译器分别处理,因此您不必担心两个不同的源文件包含相同的头文件。

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. 这就是为什么在头文件(pragmas或#ifndef ... )中包含防护是C编程中广泛采用的习惯用法的原因。

Another problem that will happen is that both c1.c and c2.c will get their own ns. 将会发生的另一个问题是c1.c和c2.c都将获得自己的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. 惯例是在一个c文件中定义ns,将其作为extern放在头文件中,并能够在其他c文件中使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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