post  Objects like std::cout and std::cin

tluisrs (4)   Link to this post
Hi everyone. I'm new in this forum. I'll try to help anyone I could.

I wanna create 2 objects like std::cout and std::cerr. I've been constructing a log system. I'll write the files here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//File Log.h
#ifndef _LOG_
#define _LOG_

class Log {
    
    int x;

    Log& operator<< (char* text);

};

#endif


So, I created another file, called LogUtil.h, that contain my objects.

1
2
3
4
5
6
7
8
9
//File LogUtil.h

#ifndef _UTILS_
#define _UTILS_

Log lcout;
Log lcerr;

#endif 


The problem I've got is that when I try to include LogUtil.h twice or more times, I've got the link error that "Log lcout" is already define in another file.

I tried Singleton desing pattern, but I've got the same error. If everyone know how do I solve this problem, please help me.
jsmith (3570)   Link to this post
Do not instantiate global variables in header files. That results in duplicate symbol link errors.

Your LogUtil.h file should have

1
2
extern Log lcout;
extern Log lcerr;


and LogUtil.cpp should instantiate them.
tluisrs (4)   Link to this post
Hi jsmith

but when I put on LogUtil.h

1
2
extern Log lcout;
extern Log lcerr;


I'll not instaciante then?
helios (5727)   Link to this post
No. The extern keyword tells the compiler that the symbol being declared is defined in a different file.
It's like when you declare and define a function in two different files, only with variables and objects, extern must be used.

This topic is archived - New replies not allowed.