【发布时间】:2014-09-21 01:08:26
【问题描述】:
我在我的配置文件中为选项定义了一个结构,并在“config.h”文件中定义了一个指向该结构的指针,我使用 libconfig 读取配置文件并在文件“config.c”中定义的函数 get_config() 中设置值”。在主函数中,我初始化指向结构的指针并调用 get_config() 函数。 libconfig 运行良好,可以正确打印结构字段的值,但是当我在主函数中打印相同的字段时,它们的值不正确!
“config.h”
#include <stdio.h>
#include <stdlib.h>
#include <libconfig.h>
typedef struct
{
int buffer_size;
const char * DBusername;
const char * DBpassword;
}conf;
conf *config;
int get_config();
“config.c”
#include "config.h"
int get_config()
{
config_t cfg;
config_setting_t *setting;
config_init(&cfg);
/* Read the file. If there is an error, report it and exit. */
if(! config_read_file(&cfg, "config.cfg"))
{
fprintf(stderr, "%s:%d - %s\n", config_error_file(&cfg),
config_error_line(&cfg), config_error_text(&cfg));
config_destroy(&cfg);
return(EXIT_FAILURE);
}
if(config_lookup_int(&cfg, "buffersize", &config->buffer_size))
printf("buffersize: %d\n\n", config->buffer_size);
else
fprintf(stderr, "No 'buffersize' setting in configuration file.\n");
if(config_lookup_string(&cfg, "DBusername", &config->DBusername))
printf("DBusername: %s\n\n", config->DBusername);
else
fprintf(stderr, "No 'DBusername' setting in configuration file.\n");
if(config_lookup_string(&cfg, "DBpassword", &config->DBpassword))
printf("DBpassword: %s\n\n", config->DBpassword);
else
fprintf(stderr, "No 'DBpassword' setting in configuration file.\n");
config_destroy(&cfg);
return(EXIT_SUCCESS);
}
“store.c”
int main(){
config = (conf*) malloc(sizeof(conf));
if(get_config() == EXIT_FAILURE)
return 0;
printf("\n%s", config->DBusername);
printf("\n%s", config->DBpassword);
printf("\n%d", config->buffer_size);
}
【问题讨论】:
-
您应该包含实际代码或 SSCCE。
-
这可能是因为结构的范围(可见性)未提供给
main()函数所在的文件。包括定义结构的.h,并确保对其进行实例化struct 要么具有全局范围,要么在main()内创建一个实例化(没有价值,但可以使用) -
“要与库链接,请指定‘-lconfig’作为链接器的参数。”您如何为 makefile 执行此操作?
-
@ZuzooVn,在 Makefile.am 文件中(由于注释限制,不可能包含完整的 Makefile.am): ... ... LIBS = -lconfig $(MYSQL) ... install -data-local: $(INSTALL) srv_store.conf $(DESTDIR)$(CONFIGDIR)/srv_store.conf.default 如果测试! -f $(DESTDIR)$(CONFIGDIR)/srv_store.conf;然后 $(INSTALL) srv_store.conf $(DESTDIR)$(CONFIGDIR)/srv_store.conf; fi EXTRA_DIST= struct.h config.h db.h file.h config.cfg $(MYSQL) $(LIBS)
标签: c configuration-files libconfig