简体   繁体   中英

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:

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). 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; (NO = ... part) in all the sources, or put in in a .h and include it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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