pyotr
pyotr

Reputation: 21

CLion Linker Error with Standard Library and GCC

I am taking a class which requires the use of GCC as the compiler. I am trying to ensure CLion is using GCC, but I no matter what I do I keep getting the following error upon trying to run my file:

Scanning dependencies of target Sandbox
[ 50%] Building CXX object CMakeFiles/Sandbox.dir/main.cpp.o
[100%] Linking CXX executable Sandbox
Undefined symbols for architecture x86_64:
  "std::basic_ostream<char, std::char_traits<char> >::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))", referenced from:
      printSquare(double) in main.cpp.o
  "std::basic_ostream<char, std::char_traits<char> >::operator<<(double)", referenced from:
      printSquare(double) in main.cpp.o
  "std::ios_base::Init::Init()", referenced from:
      __static_initialization_and_destruction_0(int, int) in main.cpp.o
  "std::ios_base::Init::~Init()", referenced from:
      __static_initialization_and_destruction_0(int, int) in main.cpp.o
  "std::cout", referenced from:
      printSquare(double) in main.cpp.o
  "std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)", referenced from:
      printSquare(double) in main.cpp.o
  "std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)", referenced from:
      printSquare(double) in main.cpp.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
make[3]: *** [Sandbox] Error 1
make[2]: *** [CMakeFiles/Sandbox.dir/all] Error 2
make[1]: *** [CMakeFiles/Sandbox.dir/rule] Error 2
make: *** [Sandbox] Error 2

Here is my very simple main.cpp file I have been using to test GCC:

#include <iostream>

using namespace std;

double square(double x) {
    return x * x;
}

void printSquare(double x) {
    cout << "The square of " << x << " is " << square(x) << endl;
}

int main() {
    printSquare(10.9);
}

as well as my CMakeLists.txt file:

project(Sandbox)

set(CMAKE_CXX_STANDARD 14)

add_executable(Sandbox main.cpp)

In preferences, under Build, Execution, Deployment | Toolchains | C++ Compiler, the path is /usr/local/bin/gcc-9.

I have tried using Homebrew update and reinstall GCC, and I couldn't find any other questions on the site which had a similar problem. I am running on MacOS Catalina 10.15.2. Thank you for the help.

Upvotes: 2

Views: 1373

Answers (1)

Ron
Ron

Reputation: 1269

Make sure you target the g++ compiler (ex: /opt/local/bin/g++) under Settings->"Build, Execution, Deployment"->"C++ Compiler". You need to use the g++ compiler for C++ code, the gcc compiler is for C code which is why you will get those linker errors for the C++ standard library functions.

Upvotes: 1

Related Questions