0

I'm porting some code from Swift to C++. I was doing the following at the top of every Swift file:

private let log = os.Logger("Foo")

This defines a log variable that is local to the file. It's like static in C and C++.

If I try a similar thing in C++, in an implementation file (not header):

static MyLib::Logger log("Foo");

I get this error:

Redefinition of 'log' as different kind of symbol, previous definition is here:
/.../usr/include/c++/v1/math.h:977:1: log(_A1 __lcpp_x) _NOEXCEPT {return ::log((double)__lcpp_x);}

So it conflicts with the mathematical log function. Is there a way to keep my static log variable and somehow give it priority to resolve the name conflict error? Or do I just need to rename my log variable?

Rob N
  • 15,024
  • 17
  • 92
  • 165
  • 1
    Quick hack: Use an [anonymous namespace](https://en.cppreference.com/w/cpp/language/namespace#Unnamed_namespaces) instead of `static`. Might be enough for your purposes. `namespace { MyLib::Logger log("Foo"); }` – user4581301 Sep 08 '22 at 21:17
  • 1
    Or use the c++ math header. There log is in the namespace std, so there is no conflict. – gerum Sep 08 '22 at 21:20
  • 1
    Had to test that one to see if it would work, @gerum . [Looks like it doesn't in at least this case.](https://godbolt.org/z/d4sdn6cvo) – user4581301 Sep 08 '22 at 21:22
  • @user4581301 The anonymous namespace gets be past that line, but then when I try to _use_ the `log` later in the file, I get a similar error about an ambiguous reference. – Rob N Sep 08 '22 at 21:26
  • 1
    That's weird about the and namespace not helping. I thought that was the whole point of those headers. Huh. – Rob N Sep 08 '22 at 21:41
  • In other words, not enough for your case. I knew I should have edited in that it won't work if you actually USE `log`. And why wouldn't you use it? That's kind of the ing point, isn't it? – user4581301 Sep 08 '22 at 22:27
  • @user4581301 Your comment was still very useful to me. I'm re-learning C++ and didn't know/remember the anon namespaces. – Rob N Sep 08 '22 at 22:40

1 Answers1

0

Well there are multiple ways to do it depending on your situation but the easiest way seems to be to just rename your log to something like _log or my_log. If not you can create your own namespace and put your log there.

Vektor 007
  • 35
  • 7