puzzlecracker said:
Can someone explain why
int k;
cannot be defined in a *.h [header] file?
It certainly can.
what are general rules
for what can/cannot be placed in a *.h [header] file.
Header files are simply files that are included
near the top [head] of a *.cc [source] file or another header file.
The *.h extension is merely a convention.
Files with the *.h extension or any other extension
including no extension may be included anywhere if a fail
but probably should *not* be called header files
unless they are included somewhere near the head of the file.
There are no rules for what an/cannot be placed in a header file
except when the header file is used to define a *module interface*
which is the most common use for a header file.
Like all other interfaces, a module interface has *no* substance.
It should not, by itself, cause the compiler to emit code
or reserve memory for data. It should not, for example,
contain definitions like:
int k;
which would compel the compiler to reserve memory for k.
It may contain type definitions and declarations like:
extern int k;
void f(void);
inline
int g(int i) {
return i + 1;
}
class X {
private:
int I;
public:
X(int i = 0): I(i) { }
};
etc.
A module interface (header file) should be idempotent.
The contents should be enclosed in "guard macros:
#ifndef GUARD_FILE_H
#define GUARD_FILE_H 1
// contents
#endif//GUARD_FILE_H
The module definition (header file) should be self-sufficient.
It should include every module interface (header file)
required to process it's contents.
[The C++] FAQ doesn't seem to address this problem.
The problem is that neither C or C++ possess a strong notion of modules
much less module interfaces like modula. See Modula-2
http://en.wikipedia.org/wiki/Modula-2
C and C++ programmers are obliged
to manufacture ad hoc module interfaces
and the most convenient way to do that is using header files.