Menu
Coddy logo textTech

External Files

Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 1 of 104.

In C++, code is split across multiple files and connected using #include directives.

A separate file MyClass.h

#include <string>

class MyClass {
public:
    std::string greet() {
        return "Hello from MyClass!";
    }
};

Include and use it in your main file

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

int main() {
    MyClass obj;
    std::cout << obj.greet() << std::endl;
    return 0;
}

Output:

Hello from MyClass!

Use double quotes "" for your own files and angle brackets <> for system/library headers. The #include directive copies the content of the file into your source code before compilation.

challenge icon

Challenge

Easy

Include the MyClass.h header file in main.cpp, create a MyClass object, and print the result of calling greet().

Print format: Greeting: <result>

Cheat sheet

In C++, code is split across multiple files and connected using #include directives.

Use angle brackets <> for system/library headers:

#include <iostream>
#include <string>

Use double quotes "" for your own header files:

#include "MyClass.h"

Example header file MyClass.h:

#include <string>

class MyClass {
public:
    std::string greet() {
        return "Hello from MyClass!";
    }
};

Using the header in main.cpp:

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

int main() {
    MyClass obj;
    std::cout << obj.greet() << std::endl;
    return 0;
}

Try it yourself

#include <iostream>
#include <string>
// TODO: Include the MyClass header file

int main() {
    std::string testCase;
    std::getline(std::cin, testCase);
    
    // TODO: Create a MyClass object and call greet()
    
    std::cout << "Test completed" << std::endl;
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming