2
class Config
{
    public:

        static int OUTPUT_TO_FILE;
        static int NEED_TO_TRAIN;
        static int NO_FILE_TRAIN;
        static int NEED_TO_TEST;
}

Above is my header.h file (i followed: http://weblogs.asp.net/whaggard/archive/2004/11/05/252685.aspx)

and I want to be able to do things like Config.OUTPUT_TO_FILE = true or variable = Config.NO_FILE_TRAIN;

from any file that includes config.h

I have what I want to do is clear, Just want some variable shared throughout all my cpp files.

EDIT: I'm having trouble compiling:

In my make file, I added:

hPif : src/main.o src/fann_utils.o src/hashes.o src/config.o # added the config part
    g++ src/main.o src/fann_utils.o src/hashes.o src/config.o -lfann -L/usr/local/lib -o hPif

config.o : src/config.cpp src/config.h
    g++ -c src/config.cpp

.
.
.
main.o: src/main.cpp src/config.h src/main.h src/hashes.h
    g++ -c src/main.cpp

config.cpp:

#include "config.h"

int OUTPUT_TO_FILE = false;
.
.
.

config.h:

class Config
{
    public:

        static int OUTPUT_TO_FILE;
.
.
.

Trying to call by:

#include "config.h"
...

            Config::OUTPUT_TO_FILE = true;

Error I get:

Undefined Symbols:
  "Config::OUTPUT_TO_FILE", referenced from:
      _main in main.o
      _main in main.o
NullVoxPopuli
  • 61,906
  • 73
  • 206
  • 352

4 Answers4

8

Header (Config.h):

#pragma once

class Config
{
public:
  static int OUTPUT_TO_FILE;
  static int NEED_TO_TRAIN;
  static int NO_FILE_TRAIN;
  static int NEED_TO_TEST;
};

Source (Config.cpp):

#include "Config.h"

int Config::OUTPUT_TO_FILE = 0;
int Config::NEED_TO_TRAIN = 0;
int Config::NO_FILE_TRAIN = 0;
int Config::NEED_TO_TEST = 0;

Usage (any.cpp):

#include "Config.h"

...
int variable = Config::OUTPUT_TO_FILE;
...
Naszta
  • 7,560
  • 2
  • 33
  • 49
0

In one of your source files, add something like this:

int Config::OUTPUT_TO_FILE = 1;

Now, it will be initialized on program startup. Only do this in one source .cpp file, not in multiple.

Thalur
  • 1,155
  • 9
  • 13
0

Because the class only has statics, you should be able to access them in any file which includes this header, for example..

foo.cpp

#include "Config.h"

void bar()
{
  Config::NO_FILE_TRAIN = 0; // set this value for example
}

bar.cpp

#include "Config.h"

void foo()
{
  Config::NEED_TO_TRAIN = 1; // set this value for example
}

Remember you must have an implementation file that is also compiled which actually defines the statics, i.e.

Config.cpp

int Config::OUTPUT_TO_FILE = 0; // initial value
:  //etc.
Nim
  • 33,299
  • 2
  • 62
  • 101
0

You might want to implement your Config class as a singleton.

Oh, and if you want to set OUTPUT_TO_FILE = true, you'd be better off declaring OUTPUT_TO_FILE as bool...

Christian Severin
  • 1,793
  • 19
  • 38