2

Suppose I have two translation units, both of which use std::string. I compile one of them with -O3, and the other without optimizations, then link the result together. Both object files would contain instantiated std::string, but I would expect one version to be compiled with optimizations, and the other one without. Would the linker pick only one of those during linking? If so, which one? Will the resulting executable be guaranteed to always run properly?

Update: as this looks to be implementation-specific, it would make sense to narrow this down to gcc and clang behavior, since they both implement well-defined and concrete Itanium ABI, rather than trying to approach this from the point of view of the C++ standard itself.

bogdan
  • 9,229
  • 2
  • 33
  • 48
dragonroot
  • 5,653
  • 3
  • 38
  • 63
  • 1
    `Both object files would contain instantiated std::string.` They will contain only the inlined member functions of `string`. All the rest comes with `libstdc++`. In this case the same behavior as any other inline function applies, the linker will pick one, probably the one in the first object file that you pass to the linker. I would assume that if the only thing that changes is the optimization level (and not some preprocessor defines) then you should be ok. – sbabbi Mar 14 '16 at 09:57

1 Answers1

0

As far as the C++ standard goes, this is probably as way out in far left field as it possibly can. For starters, the C++ standard has nothing to say about "optimization levels", or any of that.

So, this falls entirely within the scope of "implementation defined". The answer depends on the exact compiler/linker and the compiler/linker version you're using. The correct answer for one compiler or linker will be applicable only to that compiler or linker. A different compiler, or even a different version of the same compiler, can produce different results.

I will expect one of two results:

A) The linker will complain about merging non-identical segments, or

B) One or the other will be picked at random. Probably whichever first or last translation unit is passed to the linker.

So, in conclusion, the only way to know the answer to this question is for you to try it with whatever compiler or linker you're using, and examine the results.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • Things are only *implementation-defined* if the standard specifically says that they are (and this means the implementation must document it). – M.M Mar 14 '16 at 02:17
  • I've updated the question to narrow it down to something more concrete. – dragonroot Mar 14 '16 at 06:33
  • Also, I'd say the more important part is whether the resulting executable would run correctly, which is more of an ABI question. – dragonroot Mar 14 '16 at 06:35