Ashish Agarwal
Ashish Agarwal

Reputation: 14925

C++ error - Undefined symbols for architecture x86_64:

I am learning C++ and have a simple Date class where I am trying to set a value for the Date.

Here are the source code files -

Date.h

class Date{ 
private:
    int month;
    int day;
    int year;

public:
    Date();
    void setDate(int m, int d, int y);

};

and Date.cpp

#include "Date.h"

Date::Date()
{
    month = 1;
    day = 1;
    year = 80;

};

void Date :: setDate(int m1, int d1, int y1){
    month = m1;
    day = d1;
    year = y1;
};

However, when I compile the code, I get the error message -

    Undefined symbols for architecture x86_64:
  "_main", referenced from:
      start in crt1.10.6.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status

Can someone please help ?

Thanks

Upvotes: 1

Views: 1255

Answers (2)

Matthew Hall
Matthew Hall

Reputation: 605

Every C/C++ program must have a main function which unconditionally serves as the entry point of your program's execution.

int main(int argc, char** argv) {
  Date d;
  d.setDate(11, 19, 1984);

  /* do something with this date... */

  return 0;
}

A common convention is to place this in main.cc / main.cpp and ensure, in this case, that both main.cpp and Date.cpp are compiled and linked into the same target binary. A linker will not proceed without being able to resolve main(int, char**). If this is obvious to you, then I'd simply ask you to check your linker command line to ensure that the source/object file containing main is included.

Also, random C++ best practices guideline: you should have a non-default constructor that takes the arguments that setDate does and assigns them to your member variables via an initializer list. In this case, a default constructor (no arguments) makes little sense for your concrete date class.

Upvotes: 1

austin
austin

Reputation: 5876

You're missing a main function. Add this to either a new file (like main.cpp, and include it when compiling and linking) or to your other .cpp file.

int main(int argc, char *argv[]) {  }

And put your code to run the program in the braces.

Upvotes: 5

Related Questions