3

我一直在阅读有关链接器如何工作以及围绕此过程的所有内容,以便在此(链接)问题中解释我的问题(很短,对参考感到抱歉,但它是相关的)。

问题: 如果在标题中我有一个变量声明(使用 extern),并且我想在多个源文件中使用这个变量(#包括每个课程中的头文件),我必须为此提供一个定义某处变量。问题是,如果我在某些源文件的主函数中提供定义,例如,其他文件仍然没有“看到”这个定义(这会导致链接错误)。如果我在其中一个全局范围内定义这个外部变量,它就可以正常工作,并且每个人都可以看到它。

为什么?其他文件如何访问另一个文件的全局范围?全局范围变量不是危险的吗?将变量定义放在其他什么范围内可以解决这样的链接错误?有人在标题中使用这样的外部变量声明吗?出于什么目的?

编辑:确切的示例情况在我一开始发布的链接中

4

2 回答 2

5

A few clarifications:

What you're calling a "file" is more properly called a translation unit. It doesn't matter how many files are involved. Indeed, the same file could be re-compiled (say with different #defines, etc.)

Armed with that term, we can now rephrase your question: "How can a translation unit access the global scope of another translation unit"?

Quoting from the wikipedia article on Linkage:

If the name has external linkage, the entity that name denotes may be referred to from another translation unit using a distinct declaration for that same name, and from other scopes within the same translation unit using distinct declarations.

In other words: by making sure that name as external linkage, it's in the global scope, and that's global for the program, not the translation unit.

Your remaining questions:

  1. Aren't global scope variables dangerous?

    I would never use the word "dangerous" to describe them, as I would certain standard library functions that have security flaws, etc. But I would say that can very often lead to very poorly designed code, and in the case of global variables specifically, a lot of headaches in multithreaded code. A good rule: avoid them unless you have a good reason not to.

  2. How to avoid the linkage error (in some other scope)

    No other magic declaration here: it's either visible outside the translation unit (external) or not (static). What you're probably asking for is : "What's the right way to let other modules access the variable?" And the answer is: write an accessor function (or even better, a class that manages that data with methods).

  3. Who uses this stuff and for what purpose?

    Always a hotly debated topic. Many people advise avoiding completely, but you'd be hard pressed not to find an extern in a project of sufficient size. The best reasons usually come down to the kind of things purists ignore: compatibility with legacy systems, performance, easy access for debuggers and other introspecting tools… or, of course, just cause it was easy, it was understood, and it just worked.

于 2012-12-30T08:08:31.827 回答
3

当您放置一个变量时in the main function,您定义了一个在该函数中可见的局部变量。

您必须在一个源文件的文件范围内定义变量。

于 2012-12-30T08:04:02.523 回答