[英]Static, global and multiple translation units
This consists of three questions which are linked: 这包括三个相关的问题:
1) How exactly do you end up with multiple translation units? 1)您最终如何使用多个翻译单元? Surely all the source and header files would "join" together because otherwise you would end up with code calling code which isn't part of that "program".
当然所有的源文件和头文件都会“加入”在一起,否则你最终会得到代码调用代码而不是那个“程序”的一部分。 Isn't a translation unit the same as a program?
翻译单位不是一个程序吗?
2) How do static objects/classes work with regards to multiple translation units? 2)静态对象/类如何处理多个翻译单元? If several source files in different translation units include a header which would create an object (that had a static data member) would there be a separate static data member per translation unit?
如果不同翻译单元中的多个源文件包含一个标题,该标题会创建一个对象(具有静态数据成员),那么每个翻译单元会有一个单独的静态数据成员吗?
3) Similar to question 2, do global variables get shared across multiple translation units (a bit like me suggesting they were separate programs- just compiled together???) or do global variables still act.... global across all translation units? 3)类似于问题2,全局变量是否在多个翻译单元之间共享(有点像我建议它们是单独的程序 - 只是编译在一起???)或者全局变量仍然在所有翻译单元中起作用?
1) Each source file, together with it's included header files, is called a translation unit. 1)每个源文件及其包含的头文件称为翻译单元。 It gets compiled into an object file.
它被编译成目标文件。 The linker then finally joins all object files into the final executable.
然后,链接器最终将所有目标文件加入到最终的可执行文件中。 (Simplified, but to give you a basic idea)
(简化,但给你一个基本的想法)
2) The linker will eliminate the copies. 2)链接器将删除副本。
3) Yes, see 2) 3)是的,见2)
No, they each are compiled into an object file which are subsequently linked together. 不,它们每个都被编译成一个目标文件,随后链接在一起。
If the object is declared but not defined in the header, which is the better practice, then there will just be one object defined ( assuming it is in fact defined in exactly one source file) and everyone who includes the header will have a way of programming with it. 如果对象被声明但未在标题中定义,这是更好的做法,那么将只定义一个对象( 假设它实际上只在一个源文件中定义),并且包含标题的每个人将有一个方法用它编程。
static
objects in a source file that would otherwise be in what appears to be global scope will not be accessible outside that translation unit. 源文件中的
static
对象将无法在该转换单元外部访问,否则这些static
对象将出现在全局范围内。 Outside of any class or function, static
limits scope to the translation unit. 在任何类或函数之外,
static
限制了翻译单元的范围。
Non-statically-scoped objects, yes, they do. 非静态范围的对象,是的,他们这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.