Home >Backend Development >C++ >Why Am I Getting 'Undefined Symbols' Errors When Compiling Simple C Code on macOS?
Question:
I am receiving an error when compiling a basic C program on macOS Lion.
Code:
#include <iostream> using namespace std; int main(int argc, char *argv[]) { for (int i = 0; i < 10; i++) { cout << "hi"; cout << endl; } return 0; }
Compilation Command:
cc main.cpp
Error:
Undefined symbols for architecture x86_64: "std::cout", referenced from: _main in ccBdbc76.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: _main in ccBdbc76.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: _main in ccBdbc76.o "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: _main in ccBdbc76.o "std::ios_base::Init::Init()", referenced from: __static_initialization_and_destruction_0(int, int)in ccBdbc76.o "std::ios_base::Init::~Init()", referenced from: ___tcf_0 in ccBdbc76.o ld: symbol(s) not found for architecture x86_64 collect2: ld returned 1 exit status
Answer:
This type of error typically occurs when the C code is compiled using the C front-end. While the C compiler understands and compiles the file as C , it fails during linking due to missing references to the C libraries. To resolve this issue, ensure that you are using the C compiler instead. Replace cc with g or clang when compiling the code:
g++ main.cpp clang++ main.cpp
Using the correct C compiler links the code with the necessary libraries and resolves the undefined symbol errors.
The above is the detailed content of Why Am I Getting 'Undefined Symbols' Errors When Compiling Simple C Code on macOS?. For more information, please follow other related articles on the PHP Chinese website!