Hi guys, I'm a new programmer that could use some help...
I've been reading everywhere that in general:
*each source file should have a matching header file
*the source file should #include the matching header file
*declare stuff in the header file
*define stuff in source file
Seems simple. I was playing around with it and I came upon a huge mental roadblock regarding
declaring/defining variables. Here's my problem in pseudocode:
Scenario 1:
1 2
|
// header file test.h
void test(); // declaring test()
|
1 2 3
|
// source file test.cpp
#include "test.h"
void test() cout << "moo"; // defining test()
|
This seems to work perfectly fine when I call test() in the main.cpp However, when I try this with variables:
Scenario 2 (doesn't work):
1 2
|
// header file test.h
int test; // declaring test
|
1 2 3
|
// source file test.cpp
#include "test.h"
test = 5; // defining test
|
It gives me an "expected constructor" error. Since I #include'd the header file, I thought test was already declared/constructed. After doing some reading, I found that in order to declare global variables, I have to have the extern prefix:
Scenario 3 (does work):
1 2
|
// header file test.h
extern int test; // declaring test
|
1 2 3
|
// source file test.cpp
#include "test.h"
int test = 5; // defining test
|
This only kind-of makes sense to me, since it looks like its declaring the variable twice, but ignoring it the first time. Can somebody explain to me why Scenario 2 doesn't work? I know its some kind of scope issue, but if I include the header file which has the declaration, then why can't I simply do test = 5?