473,473 Members | 1,504 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Const objects defined in headers

Hi, All:

I read the following passage from a book:

"There are three exceptions to the rule that headers should not contain
definitions: classes, const objects whose value is known at compile
time, and inline functions are all defined in headers. "

Can someone explain to me why some of the const objects must be defined
in the header file?

Thanks in advance for the help

--Rui

Aug 8 '06 #1
4 3271
* Ru*******@gmail.com:
>
I read the following passage from a book:

"There are three exceptions to the rule that headers should not contain
definitions: classes, const objects whose value is known at compile
time, and inline functions are all defined in headers. "

Can someone explain to me why some of the const objects must be defined
in the header file?
No, because (1) that's not what the quoted passage says, and (2) the C++
standard does not assume the existence of files or a file system.

As a practical matter you can define const objects in a header file.

That doesn't mean you must.

As a formal matter you can define anything in a header file.

That doesn't mean you must or should.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Aug 8 '06 #2
Hi, Alf:

Thanks a lot for the information, I am still a little confusing here,
bear with me since I am new to C++. Here is the complete section from
the book, basically it is saying that you should never put definitions
for variables or functions in header files since headers are included
in multiple source files, but for some reason, the definition for some
constants should in the header file.

from the book, C++ Primer:

"When designing a header it is essential to remember the difference
between definitions, which may only occur once, and declarations, which
may occur multiple times, Because headers are included in multiple
source files, they should not contain definitions of variables or
functions."

"There are three exceptions to the rule that headers should not contain
definitions: classes, const objects whose value is known at compile
time, and inline functions are all defined in headers. These entities
may be defined in more than one source file as long as the definitions
in each file are exactly the same.

These entities are defined in headers because the compiler needs their
definitions (not just declarations) to generate code. For example, to
generate code that defines or uses objects of a class type, the
compiler needs to know what data members make up that type. It also
needs to know what operations can be performed on these objects. The
class definition provides the needed information. That const objects
are defined in a header may require a bit more explanation."

Recall that by default a const variable (Section 2.4, p. 57) is local
to the file in which it is defined. As we shall now see, the reason for
this default is to allow const variables to be defined in header files.

In C++ there are places where constant expression (Section 2.7, p. 62)
is required. For example, the initializer of an enumerator must be a
constant expression. We'll see other cases that require constant
expressions in later chapters.

Generally speaking, a constant expression is an expression that the
compiler can evaluate at compile-time. A const variable of integral
type may be a constant expression when it is itself initialized from a
constant expression. However, for the const to be a constant
expression, the initializer must be visible to the compiler. To allow
multiple files to use the same constant value, the const and its
initializer must be visible in each file. To make the initializer
visible, we normally define such consts inside a header file. That way
the compiler can see the initializer whenever the const is used.

However, there can be only one definition (Section 2.3.5, p. 52) for
any variable in a C++ program. A definition allocates storage; all uses
of the variable must refer to the same storage. Because, by default,
const objects are local to the file in which they are defined, it is
legal to put their definition in a header file.

There is one important implication of this behavior. When we define a
const in a header file, every source file that includes that header has
its own const variable with the same name and value.

When the const is initialized by a constant expression, then we are
guaranteed that all the variables will have the same value. Moreover,
in practice, most compilers will replace any use of such const
variables by their corresponding constant expression at compile time.
So, in practice, there won't be any storage used to hold const
variables that are initialized by constant expressions.

When a const is initialized by a value that is not a constant
expression, then it should not be defined in header file. Instead, as
with any other variable, the const should be defined and initialized in
a source file. An extern declaration for that const should be made in
the header, enabling multiple files to share that variable.

I don't really understand the explanation offered by the book.

Thanks again for the help

--Rui


Alf P. Steinbach wrote:
* Ru*******@gmail.com:

I read the following passage from a book:

"There are three exceptions to the rule that headers should not contain
definitions: classes, const objects whose value is known at compile
time, and inline functions are all defined in headers. "

Can someone explain to me why some of the const objects must be defined
in the header file?

No, because (1) that's not what the quoted passage says, and (2) the C++
standard does not assume the existence of files or a file system.

As a practical matter you can define const objects in a header file.

That doesn't mean you must.

As a formal matter you can define anything in a header file.

That doesn't mean you must or should.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Aug 8 '06 #3
* Ru*******@gmail.com:
[top-posting]
Please don't top-post in this group. See the FAQ. Corrected.
* Ru*******@gmail.com:
[snip]

I don't really understand the explanation offered by the book.
C++ has a "one definition rule" (often referred to as the "ODR").

In practical terms the ODR is essentially that the linker should only be
presented with /one/ global definition of something -- whatever it is
-- unless that something is

* an 'inline' function, or

* a templated thing,

in which case the linker will simply choose one of the definitions it
encounters, and blithely assume that all others are exactly the same.

The ODR also holds within a translation unit, but (1) that's not a
problem that occurs very often in practice, and (2) within a translation
unit an ODR violation such as

void foo() {} // 1st definition
void foo() {} // 2nd definition, doesn't matter that it's the same

will be detected by the compiler.

Now, when you for example define a not-'inline' function foo in a header
file, and include that header file in more than one translation unit,
then each translation unit will generate one definition of foo, and the
linker will be presented with multiple global definitions of foo, in
violation of the ODR, and most linkers will then complain.

Here I've used the word "global" for definitions that are accessible and
used throughout the program, as opposed to accessible just locally
within a translation unit. The C++ terms are, respectively, "extern
linkage" for global access, and "internal linkage" for access restricted
to the relevant translation unit. 'const' objects that are declared
outside functions and classes have internal linkage by default, so the
ODR does not apply except if you define the same one more than once in
the translation unit's own code. Therefore, you can freely define
'const' objects in header files, as a practical matter. However,
non-'const' objects that are declared outside functions and classes have
external linkage by default, so the ODR does apply. Include that header
file in more than translation unit and the linker will be unhappy.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Aug 8 '06 #4

Alf P. Steinbach wrote:
* Ru*******@gmail.com:
[top-posting]

Please don't top-post in this group. See the FAQ. Corrected.
* Ru*******@gmail.com:
[snip]

I don't really understand the explanation offered by the book.

C++ has a "one definition rule" (often referred to as the "ODR").

In practical terms the ODR is essentially that the linker should only be
presented with /one/ global definition of something -- whatever it is
-- unless that something is

* an 'inline' function, or

* a templated thing,

in which case the linker will simply choose one of the definitions it
encounters, and blithely assume that all others are exactly the same.

The ODR also holds within a translation unit, but (1) that's not a
problem that occurs very often in practice, and (2) within a translation
unit an ODR violation such as

void foo() {} // 1st definition
void foo() {} // 2nd definition, doesn't matter that it's the same

will be detected by the compiler.

Now, when you for example define a not-'inline' function foo in a header
file, and include that header file in more than one translation unit,
then each translation unit will generate one definition of foo, and the
linker will be presented with multiple global definitions of foo, in
violation of the ODR, and most linkers will then complain.

Here I've used the word "global" for definitions that are accessible and
used throughout the program, as opposed to accessible just locally
within a translation unit. The C++ terms are, respectively, "extern
linkage" for global access, and "internal linkage" for access restricted
to the relevant translation unit. 'const' objects that are declared
outside functions and classes have internal linkage by default, so the
ODR does not apply except if you define the same one more than once in
the translation unit's own code. Therefore, you can freely define
'const' objects in header files, as a practical matter. However,
non-'const' objects that are declared outside functions and classes have
external linkage by default, so the ODR does apply. Include that header
file in more than translation unit and the linker will be unhappy.
Thanks a lot for the explanation


A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Aug 8 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: qazmlp | last post by:
const has internal linkage in C++, but external linkage in C. Am I right ? But, linker reports multiply-defined error if the following header is included in multiple .cpp files. //...
15
by: Dave | last post by:
Hello NG, It is well known that memory-allocating definitions should not be put in a header file. I believe, however, that this does not apply to const definitions. For example: #ifndef...
10
by: S.Tobias | last post by:
1. If I have a struct type which contains a const member: struct mystruct { const int id; int mutable; }; does a definition struct mystruct ms; define an object `ms' which is *partly* const? ...
16
by: recover | last post by:
#include <string> #include <iostream> using namespace std; class TConst { private: string con; string uncon; public:
2
by: Adrian | last post by:
Hi, In a header file I tried const char *someval="this is a test"; which is included all over the place and I get linker errors about multiple defines. Why is this not folded when const char...
8
by: minseokoh | last post by:
Hi, Could someone explain why "const" is located after the function name and what it means? inline unsigned char *access(int off) const { if (off < 0) abort(); return (&bits_); }
29
by: Rohit kumar Chandel | last post by:
Hi all, I have a doubt in const keyword. My understanding says that a variable declared const can not be modified by the module it is defined in. Then consider the following code segment:...
10
by: Stephen Howe | last post by:
Hi Just going over some grey areas in my knowledge in C++: 1) If I have const int SomeConst = 1; in a header file, it is global, and it is included in multiple translations units, but it...
5
by: coolguyaroundyou | last post by:
Consider the following codes: class abc { int i; public: abc() : i(0) {} void func() { .....some code....} };
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.