How do header files and source files work together in C++?

In C++, header files and source files work hand in hand to organize code and promote reusability. A header file typically has a .h extension and contains declarations of functions, classes, and variables. Source files, on the other hand, have a .cpp extension and contain the actual implementation of those declarations.

Here is a simple example demonstrating how a header file and a source file work together:

// File: example.h #ifndef EXAMPLE_H #define EXAMPLE_H void printMessage(); #endif // File: example.cpp #include #include "example.h" void printMessage() { std::cout << "Hello, World!" << std::endl; } // File: main.cpp #include "example.h" int main() { printMessage(); return 0; }

In this example, the example.h file declares the function printMessage, while example.cpp provides its definition. The main.cpp file includes the header and calls the function, which results in the output "Hello, World!"


header files source files C++ programming function declarations code organization