A Solution for undefined symbols error when compiling C++ files using cc

 

When compiling C++ files using cc , you might face an error of :

/*Error output under macOS .*/
Undefined symbols for architecture x86_64:
  "std::__1::locale::use_facet(std::__1::locale::id&) const", referenced from:
      std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::__put_character_sequence<char, std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, char const*, unsigned long) in tmp-685d18.o
...

/*Error output under freeBSD .*/
ld: error: undefined symbol: std::__1::cout
>>> referenced by tmp.cpp
>>>               /tmp/tmp-6ef42a.o:(main)

ld: error: undefined symbol: std::__1::basic_ostream<char, std::__1::char_traits<char> >::sentry::sentry(std::__1::basic_ostream<char, std::__1::char_traits<char> >&)
>>> referenced by tmp.cpp
>>>               /tmp/tmp-6ef42a.o:(std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::__put_character_sequence<char, std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, char const*, unsigned long))
...
...

This is a linker problem , an example of a source file which generates this error is :

#include<iostream>

int main(void ){
  std::cout << "Hello world" ; }

In this case the C++ standard library was used , and the linker was unable to figure it out .

This can be solved by compiling using :

$ cc -Xlinker -lc++ file.cpp
/* The -Xlinker option , is used to 
   pass arguments to the linker .
   In this case , the passed argument 
   is the library to use when 
   linking , which is the 
   c++ standard library .*/