Positive x Squared
Positive x Squared

Reputation: 47

Sublime Text 3 c++ undefined reference to classes

I'm able to compile single file code but not anything with separate file classes. This works in code blocks, but not sublime text. I couldn't find any information on this topic so I'm asking here.

Here is my code (all in one folder):

main.cpp:

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

using namespace std;

int main()
{
  Cat c;

  cout << "Hello world!" << endl;
  return 0;
}

Cat.cpp:

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

using namespace std;

Cat::Cat()
{
  cout << "i am cat bboiii";
}

Cat.h:

#ifndef CAT_H
#define CAT_H


class Cat
{
    public:
        Cat();
};

#endif // CAT_H

Upvotes: 0

Views: 1801

Answers (1)

romeric
romeric

Reputation: 2385

Your issue is most definitely with your Makefile. Whenever you split your code into header and source files you need to tell your compiler where to find those header files.

g++ -I/path/to/header Cat.cpp main.cpp -o Cat

The -I flag tells the compiler to include header files from the path you give it. If all your files are in one folder (which in your case they are), you can simply compile them as

g++ -I. Cat.cpp main.cpp -o Cat

where . stands for the current directory or

g++ Cat.cpp main.cpp -o Cat

as the compiler looks for headers in the current directory by default. As your project size grows, you will need to prepare your Makefile to automate the build process. The simplest Makefile would be

all:
   g++ Cat.cpp main.cpp -o Cat

and then you simply run make in the directory containing your makefile. I suggest you read this answer on how to make practical makefiles.

Upvotes: 1

Related Questions