Home >Backend Development >C++ >Why Am I Getting 'Undefined Symbols' Errors When Compiling Simple C Code on macOS?

Why Am I Getting 'Undefined Symbols' Errors When Compiling Simple C Code on macOS?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-09 01:43:14566browse

Why Am I Getting

Error Compiling Simple C Code

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> > &amp; std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> > &amp;, char const*)", referenced from:
      _main in ccBdbc76.o
  "std::basic_ostream<char, std::char_traits<char> > &amp; std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> > &amp;)", referenced from:
      _main in ccBdbc76.o
  "std::basic_ostream<char, std::char_traits<char> >::operator<< (std::basic_ostream<char, std::char_traits<char> > &amp; (*)(std::basic_ostream<char, std::char_traits<char> > &amp;))", 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn