llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
28.68k stars 11.86k forks source link

operator<<(ostream, string) declared in <string> but defined in <ostream> #40908

Open smeenai opened 5 years ago

smeenai commented 5 years ago
Bugzilla Link 41563
Version unspecified
OS All
CC @dwblaikie,@yeputons,@loskutov,@ldionne,@mclow

Extended Description

$ cat f.cpp
#include <iosfwd>
#include <string>
void f(std::ostream &os) { os << std::string("Hello world!\n"); }

$ cat main.cpp
#include <iostream>
#include <string>
void f(std::ostream &);
int main() { f(std::cout); }

$ clang++ f.cpp main.cpp
Undefined symbols for architecture x86_64:
  "std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::operator<<<char, std::__1::char_traits<char>, std::__1::allocator<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)", referenced from:
      f(std::__1::basic_ostream<char, std::__1::char_traits<char> >&) in f-e729ff.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

The operator<<(ostream, string) overload is declared in <string> but defined in
<ostream>, so if you just include <string>, you end up with an undefined reference
to it which results in a link error, as demonstrated above. It links successfully
if I change f.cpp to include <ostream> instead of <iosfwd>.

I don't know if this would necessarily be considered a bug, but I find it strange
that you can end up in a situation where you include a header and have all the
declarations needed to compile, but then have to pull in another header to actually
be able to link.

My above test case was run with Xcode 10.2, but in theory you should have the same
issue with upstream libc++.
yeputons commented 4 years ago

Any updates?

I was able to reproduce this issue (very similar code) at:

  1. Wandbox: https://wandbox.org/permlink/0V1jdpPbUFS2tR6I
  2. Ubuntu 16.04.1 LTS with clang version 10.0.0-++20200412072846+50d7e5d5e7d-1~exp1~20200412053445.132 and libc++-10 most recent releases installed from https://apt.llvm.org

This bug also appears in the wild: https://github.com/onqtam/doctest/issues/356 , https://github.com/onqtam/doctest/issues/126 .

llvmbot commented 5 years ago

I'll take a look.