[英]What is the difference between declaring a variable in a header instead of the source file (cpp/h)
Are there any difference between declaring variables in a header and declaring variables in a source code ? 在标头中 声明变量和在源代码中声明变量之间有什么区别吗? eg perfomance , securities
例如性能 , 证券
There is no difference at all. 完全没有区别。 Except they are best written in such a way that it supports:
除非它们最好以支持以下方式编写:
A header is often written so that it doesn't declare its contents multiple times. 通常会写一个标头,以便它不会多次声明其内容。
#ifndef __THIS_HEADER_H #define __THIS_HEADER_H 1 .... (content of header which is protected from multiple insertions) #endif
A module may include a .c
file, but this is rare (and non-recommended) usage: 一个模块可能包含一个
.c
文件,但是这种用法很少(不推荐):
ac: 交流电:
#define PERSONALITY 1
#include "main_logic.c"
bc: 公元前:
#define PERSONALITY 2
#include "main_logic.c"
main_logic.c: main_logic.c:
#if PERSONALITY == 1
int main (void)
{
printf ("personality 1\n");
}
#endif
#if PERSONALITY == 2
int main (void)
{
printf ("personality 2\n");
}
#endif
Declaring variables in the header makes them available to all files that include this header using #include<...>
. 在标头中声明变量使它们可以使用
#include<...>
包含在所有包含此标头的文件中。 Declaring it in the cpp file makes them available to the code in this file only. 在cpp文件中对其进行声明将使其仅可用于此文件中的代码。
This is because of the way cpp and h files work together. 这是因为cpp和h文件一起工作的方式。
The h file contains all the declarations, while the corresponding cpp file should contain the code for these declarations. h文件包含所有声明,而相应的cpp文件应包含这些声明的代码。
Please (also for future readers) note that using only h files in order to avoid a seemingly complex situation is very bad practice, because you would then not be using a very good language feature and it would make it (with the exception of using classes) impossible to separate private from public functions and variables. 请 (也供将来的读者使用)请注意,仅使用h文件来避免看似复杂的情况是非常糟糕的做法,因为那样的话,您将不会使用非常好的语言功能,并且会做到这一点(使用类除外) )无法将私有函数与公共函数和变量分开。
Also, on another note: h files are distributed, while their code (which is in the cpp file is compiled into a binary. So for the sake of not reveling your code to everyone and keeping the header files small, you should split this appropriately. 另外,还有一点需要注意: h文件是分布式的,而它们的代码( cpp文件中的代码则被编译为二进制文件。因此,为了不向所有人公开您的代码并使头文件保持较小,您应该适当地将其拆分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.