redefinition of '...'
The redefinition of '...' error means the same identifier is defined twice in the same scope. Unlike the linker error, this is caught during compilation.
What It Means
The compiler encountered a second definition of a name that was already defined in the current scope. In C++, you cannot declare the same variable or function twice in the same block or namespace scope.
Why It Happens
- A variable is declared twice in the same function or block
- A header file is included twice without include guards
- A function is defined twice in the same translation unit
- A macro expands to code that creates duplicate definitions
- Copy-paste errors where a variable declaration is duplicated
How to Fix It
Step 1: Remove duplicate variable declarations
#include <iostream>
int main() {
int count = 10;
int count = 20; // error: redefinition of 'count'
std::cout << count << std::endl;
return 0;
}// fixed
int main() {
int count = 20; // single declaration
std::cout << count << std::endl;
return 0;
}Step 2: Add header guards
// config.h — WITHOUT guard
int TIMEOUT = 30;// main.cpp
#include "config.h"
#include "config.h" // included twice — redefinition of TIMEOUT!
// config.h — WITH guard
#ifndef CONFIG_H
#define CONFIG_H
int TIMEOUT = 30;
#endifFor class definitions, the guard prevents duplicate type definitions:
// point.h
#ifndef POINT_H
#define POINT_H
struct Point {
int x, y;
};
#endifStep 3: Fix duplicate function definitions
#include <iostream>
int add(int a, int b) {
return a + b;
}
int add(int a, int b) { // redefinition of 'add'
return a + b;
}
int main() {
std::cout << add(2, 3) << std::endl;
return 0;
}// fixed — remove the duplicate
int add(int a, int b) {
return a + b;
}Step 4: Check for typedef redefinitions
typedef int Length;
typedef int Length; // error: redefinition of 'Length'
In C++11 and later, using aliases have the same restriction:
using Length = int;
using Length = int; // error: redefinition
Fix: Use only one type alias, or wrap in header guards.
Step 5: Use #pragma once as an alternative
// point.h
#pragma once
struct Point {
int x, y;
};#pragma once is supported by all major compilers (GCC, Clang, MSVC) and is simpler than traditional include guards. Note that it is not part of the C++ standard but works universally in practice.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro