[英]C++: I have this config class that I want to use between all my CPP files, how do I initialize it?
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 ) 上面是我的header.h文件(我遵循: 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; 我希望能够做像Config.OUTPUT_TO_FILE = true或variable = Config.NO_FILE_TRAIN这样的事情;
from any file that includes config.h 来自任何包含config.h的文件
I have what I want to do is clear, Just want some variable shared throughout all my cpp files. 我想要做的就是清楚,只想在我的所有cpp文件中共享一些变量。
EDIT: I'm having trouble compiling: 编辑:我在编译时遇到问题:
In my make file, I added: 在我的make文件中,我添加了:
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: config.cpp:
#include "config.h"
int OUTPUT_TO_FILE = false;
.
.
.
config.h: 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
Header (Config.h): 标题(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): 来源(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): 用法(any.cpp):
#include "Config.h"
...
int variable = Config::OUTPUT_TO_FILE;
...
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.
仅在一个源.cpp文件中执行此操作,而不是多个。
Because the class only has statics, you should be able to access them in any file which includes this header, for example.. 因为类只有静态,所以你应该能够在包含这个头的任何文件中访问它们,例如..
foo.cpp Foo.cpp中
#include "Config.h"
void bar()
{
Config::NO_FILE_TRAIN = 0; // set this value for example
}
bar.cpp 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, ie 请记住,您必须具有一个实际文件,该文件也已编译,实际上定义了静态,即
Config.cpp Config.cpp
int Config::OUTPUT_TO_FILE = 0; // initial value
: //etc.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.