Home >Backend Development >C++ >Why Should You Avoid Including .cpp Files Instead of .h Files?

Why Should You Avoid Including .cpp Files Instead of .h Files?

Barbara Streisand
Barbara StreisandOriginal
2024-11-27 19:20:11976browse

Why Should You Avoid Including .cpp Files Instead of .h Files?

Including .cpp Files: Does It Introduce Duplicates?

In a programming context, header files (.h) and source files (.cpp) play crucial roles. Header files contain function and class declarations, enabling other modules to interact with them. While it's generally recommended to include header files, a question arises: Can you include source files (.cpp) directly instead?

The answer is a resounding "no." Including .cpp files can lead to multiple definition errors. To understand why, let's examine the following code:

// main.cpp
#include <iostream>
#include "foop.h"

int main() {
  int x = 42;
  std::cout << x << std::endl;
  std::cout << foo(x) << std::endl;
  return 0;
}
// foop.h
#ifndef FOOP_H
#define FOOP_H
int foo(int a);
#endif
// foop.cpp
int foo(int a) {
  return ++a;
}

With the header file included, the code compiles and runs without issues. However, let's say we mistakenly include the source file (.cpp) instead of the header file:

// main.cpp
#include <iostream>
#include "foop.cpp"

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

In this scenario, the compiler throws an error:

multiple definition of foo(int)
first defined here

What's causing this error? When the preprocessor includes a source file (.cpp), it copies the entire content of that file into the current file. So, essentially, the following code would be generated:

// main.cpp
#include <iostream>

int foo(int a) {
  return ++a;
}

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

As you can see, the function foo() is now defined twice in the same file, leading to a multiple definition error. To avoid this issue, it's crucial to include header files (.h) instead of source files (.cpp). Header files declare functions and classes without their implementations, preventing duplication and ensuring that only one definition of each function exists in the entire program.

The above is the detailed content of Why Should You Avoid Including .cpp Files Instead of .h Files?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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