Originally Posted by
Daved
The question I still have is whether the extern is necessary for constants.
It seems not to be. Actually, I have no trouble getting it to work without extern, and I was also able to compile with extern const int j declared in a header and defined in the "main" source file. But I can't figure out how to compile with the constant declared as extern in a header and defined in a separate source file. This set of files gives me two "undefined reference to 'j'" errors. (It compiles all 3 ".o" files, but doesn't link them.) Can you tell me what's wrong?
Code:
#ed: commented out the following 2 lines as they were not serving any purpose in this makefile
#CXX = g++
#CCFLAGS = -g -Wall
scopetest: source1.o source2.o constants.o
g++ source1.o source2.o constants.o -o scopetest
source1.o: header1.h header2.h source1.cc
g++ -c source1.cc
source2.o: header1.h header2.h source2.cc
g++ -c source2.cc
constants.o: constants.cc
g++ -c constants.cc
clean:
rm *.o scopetest
Code:
// header1.h
#ifndef header1_h
#define header1_h
static int i = 4;
extern const int j;
//const int j = 6;
int dosomething();
#endif
Code:
// header2.h
namespace {
const int c = 5;
}
Code:
// source1.cc
#include "header1.h"
#include "header2.h"
#include <iostream>
using namespace std;
//const int j = 6;
int main() {
dosomething();
++i;
dosomething();
cout << "in main, i = " << i << endl;
cout << "in main, c = " << c << endl;
cout << "in main, j = " << j << endl;
dosomething();
}
Code:
// source2.cc
#include "header1.h"
#include "header2.h"
#include <iostream>
using namespace std;
int dosomething() {
cout << "in source2.cc, i = " << i << endl;
cout << "in source2.cc, c = " << c << endl;
cout << "in source2.cc, j = " << j << endl;
return i;
}
Code:
// constants.cc
const int j = 6;