1

While implementing class member functions in.cpp file on macOS 10.15, displaying an error:

clang: Undefined symbols for architecture x86_64:error:

"Circle::Area()", referenced from:
      _main in main-4cfa92.o

"Circle::Circle(double)", referenced from:
      _main in main-4cfa92.o

linker command failed with exit code 1 (use -v to see invocation)

To verrify this case, I found an example on the website to try, and it worked fine when I copied the function definitions from Circle.cpp file into Circle.h file, But when the function declaration is in Circle.h and function definition is in Circle.cpp files, respectively, an error occurs

//Circle.h

#ifndef CIRCLE_H
#define CIRCLE_H

class Circle
{
private:
    double r;//radius
public:
    Circle();//constructor
    Circle(double R);//The constructor
    double Area();//computing area
};

#endif
//Circle.cpp

#include "Circle.h"

Circle::Circle(){
    this->r=5.0;
}
Circle::Circle(double R){
    this->r=R;
}
double Circle::Area(){
    return 3.14*r*r;
}
//main.cpp

#include <iostream>
#include "Circle.h"

using namespace std;

int main(){
    Circle c(3);
    cout<<"Area="<<c.Area()<<endl;
    return 0;
}

Error message:

Undefined symbols for architecture x86_64:
  "Circle::Area()", referenced from:
      _main in main-4cfa92.o
  "Circle::Circle(double)", referenced from:
      _main in main-4cfa92.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
赵楚涵
  • 13
  • 4
  • 4
    Possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Yksisarvinen Sep 09 '19 at 09:58
  • 3
    tl;dr of the dupe - You need to compile and link all cpp files together. Never really used clang, but probably it looks like in gcc - `clang [flags] main.cpp Circle.cpp` – Yksisarvinen Sep 09 '19 at 09:59
  • 1
    @Yksisarvinen Indeed it does. It would be useful if the OP posted what build system they are using. It looks like they are compilng each source file by hand, which is hard work even for pros. – trojanfoe Sep 09 '19 at 10:12
  • @Yksisarvinen thanks, I run it though Visual Stdio Code extension: coderunner, and it automatic compiles only one cpp file at a time – 赵楚涵 Sep 09 '19 at 11:09

1 Answers1

1

Looks like you have not included Circle.cpp in the compilation step. Make sure you include both main.cpp and Circle.cpp

Sagar Sakre
  • 2,336
  • 22
  • 31