Home > Backend Development > C++ > Why Should I Include Header (.h) Files Instead of Implementation (.cpp) Files in C ?

Why Should I Include Header (.h) Files Instead of Implementation (.cpp) Files in C ?

Barbara Streisand
Release: 2024-11-26 01:06:12
Original
546 people have browsed it

Why Should I Include Header (.h) Files Instead of Implementation (.cpp) Files in C  ?

Including .cpp Files: A Case of Function Duplication

When developing in C , it is generally recommended to include header (.h) files for functionality, rather than implementation (.cpp) files. Including .cpp files can lead to errors due to function duplication.

Let's consider the following code example:

// main.cpp
#include <iostream>
#include "foop.h" // Header file containing the function declaration

int main() {
  std::cout << foo(42) << std::endl;
  return 0;
}

// foop.h
int foo(int a); // Function declaration

// foop.cpp
int foo(int a) { // Function definition
  return ++a;
}
Copy after login

This code will compile and run correctly because the header file (.h) only includes the declaration of the foo() function, while the definition is provided in the separate .cpp file.

However, if we replace the header file inclusion in main.cpp with the .cpp file inclusion:

// main.cpp
#include <iostream>
#include "foop.cpp" // Implementation file containing the function definition
Copy after login

This will result in a compiler error:

multiple definition of foo(int)
first defined here
Copy after login

This is because the preprocessor copies the contents of the included file into the main source file. Including the .cpp file effectively copies the foo() function definition into main.cpp, which results in a duplicate definition of the function.

To avoid function duplication, it is recommended to include header (.h) files only for declarations and .cpp files for definitions. This helps ensure that functions are defined only once in the program.

The above is the detailed content of Why Should I Include Header (.h) Files Instead of Implementation (.cpp) Files in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template