0

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?

Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • Can you not use `extern` to share the variable? http://stackoverflow.com/questions/10422034/when-to-use-extern-in-c – NathanOliver Aug 05 '15 at 15:15
  • it's `static` so you can't access it fro outside of the translation unit it's defined in. – Captain Obvlious Aug 05 '15 at 15:15
  • Sorry, it is defined as extern, question updated. I know it gets shared within the project, but I want to pre-declare the var in the library - so the symbol can be used - without actually defining it. – Mr. Boy Aug 05 '15 at 15:17
  • May I suggest that having a library reach into the app for a global variable is very bad coupling? If the app needs to set the value, you should have a "set" function in the library that is called by the app and store the value in the library itself. – Mark Ransom Aug 05 '15 at 16:21

1 Answers1

4

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.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252