简体   繁体   English

引用在从属应用程序中声明的库中的变量

[英]Reference a variable in a library that's declared in a dependent application

I can't remember what the rules are here, in my application project I currently declare a global variable in stdafx.h/cpp: 我不记得这里有什么规则,在我的应用程序项目中,我目前在stdafx.h / cpp中声明了一个全局变量:

extern const char *LOGFILE = "test.log"

I've found that a library needs to know the value of this variable. 我发现一个库需要知道该变量的值。 Can I forward declare it in the library since it's not linked until the application is built, without getting errors about multiply-defined symbols? 我可以在库中向前声明它,因为它直到应用程序构建时才链接,而不会出现关于乘法定义符号的错误?

The rules are : an extern variable can be declared (no =... ) in as many compilation units as you need (and even more than once in any of them). 规则是:可以根据需要在任意数量的编译单元中声明 extern变量(no =... )(并且在任何一个中可以声明多个)。 It shall be defined (with =... ) exactly once in the whole program. 在整个程序中,它应该只定义一次 (用=... )。

So if you want to write a library that uses this variable, you can safely declare it in any compilation unit of the library that needs it : you will be able to compile the library objects and generate the library itself with no error. 因此,如果要编写使用此变量的库,则可以在需要该库的任何编译单元中安全地声明它:您将能够编译库对象并生成库本身而不会出错。 There will be an unresolved symbol in the library, that will be resolved at link time when building the excutable at at load time if it is a shared library. 库中将有一个未解析的符号,如果它是共享库,则在加载时构建可执行文件时将在链接时解析。

You can either write extern const char *LOGFILE; 您可以编写extern const char *LOGFILE; (NO = ... part) in all the sources, or put in in a .h and include it. (NO = ... part)在所有来源中,或放入.h并将其包括在内。

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

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