0

I just had strange effects in my program because of two different classes with the same name in two different cpp files of a DLL. I thought that code in cpp files does not influence code in other cpp files, but this is obviously wrong.

Is it true that because of ODR, a class name must be unique across the whole program, including all interface classes of other DLLs? I assume that non-interface classes in other DLLs have been compiled away and cannot cause trouble.

Fabian
  • 4,001
  • 4
  • 28
  • 59
  • Object files generated from your source files a linked together and can most certainly influence eachother. To make something isolated to a single cpp file (compilation unit) you need to either make it `static` or place it in a unnamed / anonymous namespace. – Jesper Juhl May 14 '20 at 06:45
  • The linker matches functions required by translation units only by name, so the list of names that the linker sees must be unique (excluding inlines, templates, and some other esoteria). Didn't understand what is the name duplication you're facing exactly: a class from your main exe and a non-interface class within a DLL? Or two classes from DLLs? Interface or not? – Ofek Shilon May 14 '20 at 06:46
  • 2
    Putting all declarations inside cpp files inside the anonymous namespace avoids these problems – Alan Birtles May 14 '20 at 06:55
  • @OfekShilon My accidental name collision was from two cpp files in the same DLL. No compiler or linker error. – Fabian May 14 '20 at 07:02
  • @Fabian By the C++ standard the linker is not required to emit errors in such cases, but some linkers do anyway. Are both your classes dllexported? What is your exact symptom - your exe is using the unexpected class implementation? Can you post a minimal repro? – Ofek Shilon May 14 '20 at 07:06
  • Anyway, the statement in your question is true: "a class name must be unique across the whole program, including all interface classes of other DLLs" (again, excluding templates and other inlines) – Ofek Shilon May 14 '20 at 07:08
  • The two classes are predicate classes for sort() and not dllexported. In one case, the wrong one from the other cpp is used. The result is merely an incorrectly sorted array but in Debug mode bad memory access is detected because the shorter class is used while the longer one is expected to be used. UB land. – Fabian May 14 '20 at 08:42
  • Related: https://stackoverflow.com/a/26052100/4675398 – Fabian Jun 08 '20 at 04:36

0 Answers0