In C programming, "multiple definition" compilation errors often occur. This is because multiple variables, functions, or objects with the same name are defined in the program. These variables, functions, or objects are all considered to be the same by the compiler, so the compiler will generate a "multiple definition" error.
In actual programming, how should we avoid and solve such problems?
In C, we can define some reused functions or variables in header files, so that we can avoid using them in multiple files. Define the same function or variable repeatedly. When using these functions or variables, we only need to include the header file.
Sample code:
//header.h
int add(int a, int b );
//source1.cpp
int add(int a, int b){
return a + b;
}
//source2.cpp
int add(int a, int b){
return a - b;
}
In this sample code, we define a header file "header.h" and define a function "add" in it. In the two source files "source1.cpp" and "source2.cpp", we define the implementation of the "add" function respectively. When we compile these two source files, the compiler will point the call to the "add" function to the definition in the header file, thus avoiding the "multiple definition" error.
In C, we can use the "static" keyword to mark a variable or function as "static" to avoid multiple files Repeated definition.
Sample code:
//source1.cpp
static int num;
//source2.cpp
static int num;
In this sample code, we define a static variable "num" in two source files respectively. Due to the "static" keyword, the compiler will treat these two variables as two different variables without causing the "multiple definition" error.
In C, we can use namespaces to avoid repeated definitions of variables, functions, or objects.
Sample code:
//source1.cpp
namespace A{
int num;
}
//source2.cpp
namespace A {
int num;
}
In this sample code, we have defined the same namespace "A" in both source files and the same variable in that namespace" num". Since the namespace solves the problem of naming conflicts, the compiler will not report a "multiple definition" error.
To sum up, we can avoid repeated definitions of variables, functions or objects by using header files, static keywords and namespaces. In actual development, we should choose the appropriate method according to needs and abide by certain coding standards, so as to reduce compilation errors and debugging time as much as possible.
The above is the detailed content of C++ compilation error: multiple definitions, how to modify them?. For more information, please follow other related articles on the PHP Chinese website!