简体   繁体   中英

Setting global pointer

I'm using an external library that has some logging and you can change the log directory,

external_library.hpp

extern char const* _log;

external_library.cpp

char const* _log = "path_to_log.log";

In my own project I have:

settings.cpp

#include "external_library.hpp"
void set_log_path() {
 std::string _p = "new_path_log.log";
 char const* _log = _p.c_str();
}

and I'm looking to simply change the log path, what I have does not work but it does not give any errors either and if I do:

#include "external_library.hpp"
void set_log_path() {
 std::string _p = "new_path_log.log";
 _log = _p.c_str();
}

I get _log is undefined or:

#include "external_library.hpp"
char const* _log;
void set_log_path() {
 std::string _p = "new_path_log.log";
 _log = _p.c_str();
}

gives me:

1>external_library.lib(assert.obj) : error LNK2005: "char const * const _log" (?external_library_assert_log@@3PEBDEB) already defined in _functions.obj

How is it I do this properly?

The problem with your approach is that the value returned by _p.c_str() becomes invalid as soon as set_log_path exits. This is because the C string is owned by std::string that gets destroyed.

Since header file external_library declares _log with extern keyword, this should work:

#include "external_library.hpp"
void set_log_path() {
   _log = "new_path_log.log";
}

If you need to construct log path dynamically, make a static char[] buffer of suitable size, format the path into it, and set _log to point to that buffer.

Alternatively, you could make your std::string _p static in the function to avoid the destructor call upon exiting the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM