using extern type (getting linker error)

Hi,

Having some trouble with using the extern type.Here is how I have it layed out:

//example header file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
enum colours {Red,Blue,Green,Alpha};
extern colours colour_Type;

class example
{
public:

    void Foo() {
        if (colour_Type == Red) {
        //do stuff set a breakpoint
        }
        else if (colour_Type ==Blue) {
        // do stuff set a breakpoint
        }
    }
};


Above shows usuage of the extern enum type 'colour_Type'. I get the following error: fatal error LNK1120: 1 unresolved externals

Now if I comment out the usuage of the enum type 'colour_Type' I get no error. However, I need to be able to decalre it and use it as extern. In order to reference it in main without including the whole example.h file. Possible? Yes! But how?


When I try and declare it in main (and as I have explained without including the example.h file)

1
2
3
4
5
6
7
8
//main source
#include <iostream>
//global varaible
colours colour_Type = Red; //errors
int main() {
//do stuff
return 0;
}


The error is: missing type specifier - int assumed. Note: C++ does not support default-int

Last edited on
Firstly, you should avoid using globals because they're horrible.

Secondly, if you want to do this, you must instantiate the global in one and only one cpp file.

You can do this like so:

1
2
3
4
// example.h

enum colours {Red,Blue,Green,Alpha};
extern colours colour_Type;

1
2
3
4
// one_and_only_one_cpp_file.cpp
#include "example.h"

colours colour_Type = Red;  // or whatever color you want 
Thanks for the reponse. It works! Are you sure this is not possible without including the header? I'd like it to be.
Last edited on
You have to include the header where colours is defined (and Red).
lampshade wrote:
Are you sure this is not possible without including the header?
It is possible. Sometimes you may decide not to include a header in order to decrease the compilation dependencies. (This would in turn decrease the build time.)

In this case, you can simply act on behalf of the preprocessor and paste the contents of the header everywhere it is included. (Generally though, this would not make the build shorter, as to what I was referring earlier.)

Regards
Topic archived. No new replies allowed.