开发者

Undefined reference to external variable

Having problems with a custom logging system I've made. I am declaring an ofstream within my main file so that it is accessible by static functions within my class. This works for my static function (ilra_log_enabled). However, this does not work on my overloaded function for the class. I receive a undefined reference to "logfile" erro开发者_运维百科r.

Any ideas?

#ifndef ILRA_H_
#define ILRA_H_

// System libraries
#include <iostream>
#include <ostream>
#include <sstream>
#include <iomanip>
#include <fstream>

// Namespace
using namespace std;

// Classes
class ilra
{
    static int ilralevel_set;
    static int ilralevel_passed;
    static bool relay_enabled;
    static bool log_enabled;
    static ofstream logfile;
public:
    // constructor / destructor
    ilra(const std::string &funcName, int toset)
    {
        // we got passed a loglevel!
        ilralevel_passed = toset;
    }
    ~ilra(){};

    static void ilra_log_enabled(bool toset){
        log_enabled = toset;

        if (log_enabled == true){
            // get current time
            time_t rawtime;
            time ( &rawtime );

            // name of log file
            string logname = "rclient-";
            logname.append(rawtime + ".txt");

            // open a log file
            logfile.open(logname.c_str());
        }
    }

    // output
    template <class T>
    ilra &operator<<(const T &v)
    {
        if(ilralevel_passed <= ilralevel_set)
            std::cout << v;
        if(log_enabled == true)
            logfile << "Test"; // undefined reference to ilra::logfile
        return *this;
    }

};  // end of the class

#endif /* ILRA_H_ */


I think the issue is that you declare logfile inside your overloaded method. It's already declared globally and by declaring it in the method you hide the global instance.

Since your other use of logfile works, I suppose you have a ofstream logfile; declaration in some cpp-file somewhere.


The extern keyword is used to inform the compiler about a variable declared outside the current scope. A declaration using extern do not define the variable. An external variable has static duration (it is allocated when the program begins and deallocated when the program ends) and has global visibility. So you need to define an extern variable, just like you do a static variable, at the scope a compilation unit (a cpp file, most ideally the file where you have defined the main() function). Doing something like this will solve your problem:

#include "ilra.h"

ofstream logfile("test.log"); // declare and define the global variable.

int main ()
{
  ilra i("hello", 1);  
  i.operator<< <int> (10);
  return 0;
}


I moved the variables to within the class and resolved the problem. Still not sure as to what was wrong with the previous method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜