IDE: C++ Builder 6.0
Project type: Console
This error occurs when:
- One header file contains the declaration of a global variable
- This global variable is not put into a namespace
- Two implementation files (.cpp) #include this header file
- The project option 'Pre-compiled headers' is not set to 'None'
Download a C++ Builder project with this error.
There are more.
Avoid using globals (recommended)
Restructure the program so you will not need to use globals. If this fails, use the Singleton Design Pattern.
Go to 'Project | Options | Compiler | Pre-compiled headers' and select 'None'. Your error message will change to the following warning:
[Linker Warning] Public symbol '_x' defined in both module MyUnit1.OBJ and MyUnit2.OBJ [Linker Warning] Public symbol '_x' defined in both module MyUnit1.OBJ and MyUnit3.OBJ
This solution is not recommended, because one should not use global data [1-5], nor work in the global namespace [6].
Suppose you have declared an integer called 'x' in a header file (.h) like below:
Put it into a namespace called 'global' like below:
Your error message will change to the following warning:
[Linker Warning] Public symbol 'global::x' defined in both module MyUnit1.OBJ and MyUnit2.OBJ [Linker Warning] Public symbol 'global::x' defined in both module MyUnit1.OBJ and MyUnit3.OBJ
This solution is not recommended, because one should not use global data [1-5], nor work in the global namespace [6].
Suppose you have declared an integer called 'x' in a header file (.h) like below:
Make it static like below:
This solution is not recommended, because one should not use global data [1-5], nor work in the global namespace [6].
- Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Item 10: 'Minimize global and shared data'
- Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Item 18: 'Declare variables as locally as possible'
- Bjarne Stroustrup. The C++ Programming Language (3rd edition).ISBN: 0-201-88954-4. Chapter 1.8.2.a: 'Don't use global data (use members)'
- Jarrod Hollingworth, Bob Swart, Mark Cashman, Paul Gustavson. Sams C++ Builder 6 Developer's Guide. ISBN: 0-672-32480-6. Chapter 3: 'Avoid using global variables'
- Jesse Liberty. Sams teach yourself C++ in 24 hours. ISBN: 0-672-32224-2. Hour 5, paragraph 'Global variables': 'In C++, global variables are avoided because they can create very confusing code that is hard to maintain.'
- Bjarne Stroustrup. The C++ Programming Language (3rd edition).ISBN: 0-201-88954-4. Chapter C.14.15: 'Don't pollute the global namespace'