Apologies for the code dump:
gameObject.cpp:
#include "gameObject.h"
class gameObject
{
private:
int x;
int y;
public:
gameObject()
{
x = 0;
y = 0;
}
gameObject(int inx, int iny)
{
x = inx;
y = iny;
}
~gameObject()
{
//
}
int add()
{
return x+y;
}
};
gameObject.h:
class gameObject
{
private:
int x;
int y;
public:
gameObject();
gameObject(int inx, int iny);
~gameObject();
int add();
};
Errors:
||=== terrac, Debug ===|
C:terracgameObject.cpp|4|error: redefinition of `class gameObject'|
C:terracgameObject.h|3|error: previous definition of `class gameObject'|
||=== Build finished: 2 errors, 0 warnings ===|
I can’t figure out what’s wrong. Help?
sellibitze
27.5k3 gold badges75 silver badges94 bronze badges
asked Sep 19, 2010 at 16:26
DataflashsabotDataflashsabot
1,3595 gold badges19 silver badges24 bronze badges
You’re defining the class in the header file, include the header file into a *.cpp file and define the class a second time because the first definition is dragged into the translation unit by the header file. But only one gameObject class definition is allowed per translation unit.
You actually don’t need to define the class a second time just to implement the functions. Implement the functions like this:
#include "gameObject.h"
gameObject::gameObject(int inx, int iny)
{
x = inx;
y = iny;
}
int gameObject::add()
{
return x+y;
}
etc
answered Sep 19, 2010 at 16:29
0
add in header files
#pragma once
answered Jan 19, 2016 at 9:34
HelperorsHelperors
2092 silver badges2 bronze badges
3
the implementation in the cpp file should be in the form
gameObject::gameObject()
{
x = 0;
y = 0;
}
gameObject::gameObject(int inx, int iny)
{
x = inx;
y = iny;
}
gameObject::~gameObject()
{
//
}
int gameObject::add()
{
return x+y;
}
not within a
class gameObject
{
}
definition block
answered Sep 19, 2010 at 16:30
fragfrag
4152 silver badges6 bronze badges
2
You should wrap the .h
file like so:
#ifndef Included_NameModel_H
#define Included_NameModel_H
// Existing code goes here
#endif
Paul Roub
36.3k27 gold badges83 silver badges92 bronze badges
answered May 10, 2016 at 17:47
zhangxiangzhangxiang
1471 silver badge1 bronze badge
1
You’re defining the same class twice is why.
If your intent is to implement the methods in the CPP file then do so something like this:
gameObject::gameObject()
{
x = 0;
y = 0;
}
gameObject::~gameObject()
{
//
}
int gameObject::add()
{
return x+y;
}
answered Sep 19, 2010 at 16:31
lockalocka
5,7693 gold badges32 silver badges38 bronze badges
If you are having issues with templates or you are calling the class from another .cpp file
try using ‘#pragma once’ in your header file.
answered Mar 15, 2019 at 3:39
1
Either try adding #pragma once
at the top of your file, or the old way… Place this at the top of your code
#ifndef GAME_H //ensuring that this object is only initialized once
#define GAME_H
and this below the last line
#endif
Which will ensure only a single initialization of the class.
answered Mar 25, 2022 at 10:25
A PA P
2,0232 gold badges23 silver badges34 bronze badges
Include a few #ifndef name #define name #endif preprocessor that should solve your problem.
The issue is it going from the header to the function then back to the header so it is redefining the class with all the preprocessor(#include) multiple times.
answered Jul 13, 2013 at 1:32
J.J.J.J.
758 bronze badges
You define the class gameObject
in both your .cpp
file and your .h
file.
That is creating a redefinition error.
You should define the class, ONCE, in ONE place.
(convention says the definition is in the .h
, and all the implementation is in the .cpp
)
Please help us understand better, what part of the error message did you have trouble with?
The first part of the error says the class has been redefined in gameObject.cpp
The second part of the error says the previous definition is in gameObject.h
.
How much clearer could the message be?
answered Sep 19, 2010 at 16:30
abelenkyabelenky
63.5k23 gold badges108 silver badges159 bronze badges
1
The redefinition of class C++ header files error happens when developers redefine the same class with identical values and commands. As a result, the inputs confuse the system because proper multiple redefinition C++ operations must have different properties and elements.
Therefore, our experts wrote this comprehensive guide explaining the redefinition of function C++ using simple examples and discussing the most common culprits that recreate the error.
So, less experienced developers and programmers should be fine with debugging the C++ error redefinition of function error from their syntax because this article answers your questions.
Contents
- Why Redefinition of Class C++ Is Invalid? 3 Common Reasons
- – Using the Game Object Command
- – Writing Ratios in Multiple Files
- Fixing the Redefinition of Class in C++: 2 Full-proof Methods
- – Correcting the Ratios
- Conclusion
Why Redefinition of Class C++ Is Invalid? 3 Common Reasons
The redefinition of class C++ inheritance error is invalid because programmers usually redefine the same class with identical commands and values. Therefore, the system does not understand the difference between both scripts, launching the redefinition of variable C++ mistakes in several code lines.
Furthermore, developers can also experience this error when writing a class in multiple files, causing a few mistakes due to repeated actions. For instance, the redefinition constructor C++ prompt must have unique values and tags because the system identifies its changes.
As a result, many programmers reported the same error when defining classes in header files. This inconvenience happens because the program drags the primary definition into a translation unit by the header file.
On the flip side, the in include file redefinition of the second message keeps the original structure that blocks further operations. In addition, the invalid message has several forms, so our experts recommend learning about the most common one.
The following example provides the typical error script:
C:terracgameObject.cpp|4|error: redefinition of `class gameObject’|
C:terracgameObject.h|3|error: previous definition of `class gameObject’|
||=== Build finished: 2 errors, 0 warnings ===|
However, learning the error’s possible culprits and syntaxes is essential when debugging the mistake from your system. Therefore, we created two chapters that recreate the error, including different elements and commands. In addition, we will show you the debugging syntaxes after.
– Using the Game Object Command
The redefinition of class error in C++ almost always happens when developers introduce the game object command without fair values. In addition, less experienced users must know this error can affect straightforward syntaxes unless they link the values correctly.
As a result, the solutions methods will not change, although your document will have different inputs. However, we will not provide the solutions in this section.
First, read the following example for the code’s first part:
class gameObject
{
private:
int x;
int y;
public:
gameObject()
{
x = 0;
y = 0;
}
gameObject(int inx, int iny)
{
x = inx;
y = iny;
}
~gameObject()
{
//
}
int add()
{
return x+y;
}
};
As you can tell, introducing game objects is not complicated because the values are similar. However, this is only the code’s initial part because another game object command launches the error.
Although the second code has fewer values and elements, it confuses the system because the developer redefines the same header class.
The following example shows the second part:
{
private:
int x;
int y;
public:
gameObject();
gameObject(int inx, int iny);
~gameObject();
int add();
};
The implementation of the CPP files is incorrect in these scripts because the system cannot link their commands and values.
Furthermore, several changes in the code are vital to helping developers and programs enable the system’s functions. First, however, let us discover why the error appears when introducing ratios.
– Writing Ratios in Multiple Files
Developers will face the same error when writing ratios in multiple files with identical values. Again, we will show you two syntaxes because the full script has several commands and documents.
Although the ratios are similar to the game object, a few prompts differ. Fortunately, debugging the error is not complicated, but let us first provide the invalid values.
Learn more about the primary code in the following example:
#include <iostream>
using namespace stb;
class Ratio{
public:
//constructor
Ratio(int m, int d){
setNum(m, d);
}
//function to set the list to numerator and denominator
void setNum (int n = 2, int d = 2){
numerator = n;
denominator = d;
}
//function to display numerator and denominator
void getNum(){
cout << numerator << “n” << denominator << endl;
}
private:
int numerator;
int denominator;
};
Although the constructors and numerators have fair values, the complete syntax must have the header file with the ratio commands. You can learn about this syntax in the following example:
#define RATIO_H
#include <iostream>
using namespace stb;
class Ratio{
public:
//constructor
Ratio(int m, int d);
//function to set the list to numerator and denominator
void setNum(int n = 2, int d = 2);
//function to display numerator and denominator
void getNum();
private:
int numerator;
int denominator;
};
#endif
Unfortunately, the second syntax cannot handle the redefinition of the same class in C++, halting further operations and changes. Therefore, it is time to discover the debugging methods that resolve the error.
Fixing the Redefinition of Class in C++: 2 Full-proof Methods
To fix the redefinition of class in C++, you should correctly define the class in both scripts. If that doesn’t fix the error, you will have to fix the value of ratios. Meanwhile, you must not determine the style for a second time for enabling function and initiating operation.
Learn how to change the script by looking at the following code:
gameObject::gameObject(int inx, int iny)
{
x = inx;
y = iny;
}
int gameObject::add()
{
return x+y;
}
As you can see, the solution is not complicated, but developers must change all elements and tags that cause the error. In addition, the next example implements the CPP files with proper forms, so keep reading for more:
{
x = 0;
y = 0;
}
gameObject::gameObject(int inx, int iny)
{
x = inx;
y = iny;
}
gameObject::~gameObject()
{
//
}
int gameObject::add()
{
return x+y;
}
This is everything developers, and programmers need to remove the annoying error by fixing the redefinitions. So now, let us discover the second option.
– Correcting the Ratios
Correcting the ratios and their values is an excellent way of debugging the syntax without affecting the rest of the document. For instance, not redefining the ratio will prevent the system from displaying errors.
Developers can use the following example for more:
Ratio::Ratio(int m, int d) {
setNum(m, d);
}
//function to set the list to numerator and denominator
void Ratio::setNum(int m, int d) {
numerator = m;
denominator = d;
}
//function to display numerator and denominator
void Ratio::getNum() {
cout << numerator << “n” << denominator << endl;
}
Furthermore, our experts suggest introducing an output stream, so this command might be essential, as shown here:
#define RATIO_H
#include <iostream>
class Ratio
{
public:
Ratio(int n, int d);
friend std::ostream& operator<<(std::ostream &os, const Ratio& r);
private:
int numerator_;
int denominator_;
};
std::ostream& operator<<(std::ostream& os, const Ratio& r)
{
os << r.numerator_ << “/” << r.denominator_ << std::endl;
return os;
}
#endif
Both examples correct the ratios and fix the bug in your system. So, developers must not change the primary and CPP files to remove the error message.
Conclusion
Creating complex documents and operations in C++ is only sometimes straightforward, as confirmed by this annoying error message. Fortunately, our guide explained many vital aspects, including the following bullet points:
- Redefining classes in C++ is not essential with multiple scripts and files
- Our experts suggest checking the primary and secondary functions before linking the commands
- Programmers can experience this error when they redefine the same class with identical values and elements
- Several programmers reported the same error when creating ratios for various purposes and with different inputs
- Debugging the error will not cause other mistakes in your document
This ultimate programmer guide is everything users need to learn how to redefine a class in C++ correctly. As a result, you will create full-proof projects and programs that no errors can harm.
- Author
- Recent Posts
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team
C++ is a powerful programming language, but like any other language, it has its quirks. One common issue that developers encounter is the “redefinition of class” error. This error occurs when the compiler encounters multiple declarations of the same class in a program. In this guide, we’ll walk you through the steps to fix this error and explain why it occurs.
Table of Contents
- Understanding the Redefinition of Class Error
- Step-by-Step Guide to Fixing the Error
- Step 1: Locate the Redefinition
- Step 2: Check for Multiple Inclusions
- Step 3: Use Include Guards
- Step 4: Use
#pragma once
- FAQ
- Related Links
Understanding the Redefinition of Class Error
The “redefinition of class” error occurs when the compiler encounters two or more declarations of the same class. This can happen for several reasons, such as:
- Copy-pasting code without modifying class names.
- Including header files multiple times in different parts of the program.
- Circular dependencies between header files.
In C++, each class should be defined only once to avoid ambiguity in the program. The compiler needs to know the exact structure of a class and its member functions to generate correct and efficient code.
Step-by-Step Guide to Fixing the Error
Step 1: Locate the Redefinition
First, you need to find the locations in your code where the class is being redefined. The error message from the compiler will usually provide the file names and line numbers of the redefinition.
For example, the error message might look like this:
error: redefinition of 'class MyClass'
In file included from main.cpp:2,
from main.cpp:5:
my_class.h:4:7: note: previous definition of 'class MyClass'
In this case, the redefinition occurs in my_class.h
at line 4.
Step 2: Check for Multiple Inclusions
Check if the same header file is being included multiple times. This can happen when the header file is included in multiple source files or when it’s included indirectly through other header files.
To identify multiple inclusions, search your codebase for #include "my_class.h"
(replace my_class.h
with the name of the header file containing the class definition). If you find it in multiple places, you might be dealing with a multiple inclusion issue.
Step 3: Use Include Guards
To prevent the same header file from being included multiple times, use include guards. Include guards are preprocessor directives that ensure a header file is included only once in a compilation unit.
Here’s how to add include guards to a header file:
#ifndef MY_CLASS_H
#define MY_CLASS_H
// Your class definition goes here
#endif // MY_CLASS_H
Replace MY_CLASS_H
with a unique identifier for your header file. This will prevent the header file from being included more than once and should fix the “redefinition of class” error if it’s caused by multiple inclusions.
Step 4: Use #pragma once
Another way to prevent multiple inclusions is to use the #pragma once
directive. This directive is supported by most modern compilers and can be a more concise alternative to include guards. Simply add #pragma once
at the beginning of your header file:
#pragma once
// Your class definition goes here
Keep in mind that #pragma once
is not part of the C++ standard, so it might not be supported by all compilers. However, it’s widely supported and is considered a safe and efficient option for preventing multiple inclusions.
FAQ
1. What is the difference between declaration and definition in C++?
In C++, a declaration introduces a name into the program and specifies its type, while a definition provides a complete description of an object or function. For example, a class declaration might look like this:
class MyClass;
A class definition includes the class’s member variables and functions:
class MyClass {
public:
int my_var;
void my_function();
};
2. Can I declare a class multiple times?
Yes, you can declare a class multiple times, as long as the declarations are identical. However, you can define a class only once in your program.
3. What is a compilation unit?
A compilation unit is a single source file (along with all the header files it includes) that is compiled into an object file by the compiler. Each compilation unit is compiled separately.
4. What are circular dependencies in header files, and how do they cause the “redefinition of class” error?
Circular dependencies occur when two or more header files depend on each other, either directly or indirectly. This can lead to multiple inclusions of the same header file, causing the “redefinition of class” error. To avoid circular dependencies, use forward declarations and include only the necessary header files.
5. Can I use both include guards and #pragma once
in the same header file?
Yes, you can use both include guards and #pragma once
in the same header file. However, it’s usually unnecessary because most modern compilers support #pragma once
. If you’re using a widely-supported compiler, you can choose either include guards or #pragma once
.
- C++ Header Files and Standard Functions
- C++ Programming/Code/Statements/Include Guards
- Understanding C++ Forward Declarations
⬆ Back to Top
Recommended Answers
The most common reason for that error is including the same header file more thn once in the same *.c or *.cpp file. To prevent the problem you need to add code guards in the header file
#ifndef MYHEADER_H #include MYHEADER_H // declare class and other stuff …
Jump to Post
That bit that says
previous definition of ‘class player’
will tell you where you already defined it. If you look at that, you’ll be able to see where you defined it already.
Sounds obvious, I know.
Jump to Post
Could you post your code if you haven’t figured it out?
Jump to Post
‘#pragma once’ is by no means bad practice, but it is non-standard, and unrecognised #pragma statements tend to be ignored rather than flagged, so it would be possible to write code that worked on one preprocessor/compiler/linker chain and not another; of course, you’d get a bunch of errors from multiple …
Jump to Post
All 16 Replies
Ancient Dragon
5,243
Achieved Level 70
Team Colleague
Featured Poster
12 Years Ago
The most common reason for that error is including the same header file more thn once in the same *.c or *.cpp file. To prevent the problem you need to add code guards in the header file
#ifndef MYHEADER_H
#include MYHEADER_H
// declare class and other stuff here
#endif
Moschops
683
Practically a Master Poster
Featured Poster
12 Years Ago
That bit that says
previous definition of ‘class player’
will tell you where you already defined it. If you look at that, you’ll be able to see where you defined it already.
Sounds obvious, I know.
12 Years Ago
Could you post your code if you haven’t figured it out?
12 Years Ago
I have tried these tips and they havn’t worked.
You don’t think it’s an issue with the compiler…
Here’s the code
class player
{
public: int money;
int roll;
int spotID;
private:
char name[45];
bool banker;
void getOriginalValues()
{
}
};
player p1,p2,p3,p4,p5,p6;
I get errors for all of the instances of the player class.
Thanx,
jt
mike_2000_17
2,669
21st Century Viking
Team Colleague
Featured Poster
12 Years Ago
>>You don’t think it’s an issue with the compiler…
It is definitely not an issue with the compiler. You can rule that out.
If there is anywhere in your code a repetition of the form “class player {“, then one of them must go.
Make sure you use the header guards.
The code you posted is not the error, unless this was part of a header file that is not guarded. It should be like so:
#ifndef PLAYER_H
#define PLAYER_H
class player
{
public: int money;
int roll;
int spotID;
private:
char name[45];
bool banker;
void getOriginalValues()
{
}
};
player p1,p2,p3,p4,p5,p6;
#endif
Edited
12 Years Ago
by mike_2000_17 because:
n/a
Moschops
683
Practically a Master Poster
Featured Poster
12 Years Ago
I have tried these tips and they havn’t worked.
I’m not convinced that you have. My tip was to look at the error message and identify the lines where you repeatedly define the same thing over and over.
Edited
12 Years Ago
by Moschops because:
n/a
Duki
552
Nearly a Posting Virtuoso
12 Years Ago
I’m not sure if it’s considered ‘bad practice’ but I typically include
#pragma once
at the beginning of all my header files.
Edited
12 Years Ago
by Duki because:
n/a
Moschops
683
Practically a Master Poster
Featured Poster
12 Years Ago
‘#pragma once’ is by no means bad practice, but it is non-standard, and unrecognised #pragma statements tend to be ignored rather than flagged, so it would be possible to write code that worked on one preprocessor/compiler/linker chain and not another; of course, you’d get a bunch of errors from multiple includes and discover the unsupported #pragma, so it wouldn’t be catastrophic.
Fbody
682
Posting Maven
Featured Poster
12 Years Ago
I have tried these tips and they havn’t worked.
You don’t think it’s an issue with the compiler…
Here’s the code
class player { public: int money; int roll; int spotID; private: char name[45]; bool banker; void getOriginalValues() { } }; player p1,p2,p3,p4,p5,p6;
I get errors for all of the instances of the player class.
Thanx,
jt
In and of itself, this code is fine. Are you positive that you have you added “header guards” as suggested? There is no indication of them in this snippet.
As long as your header guards are in place, and this is the only code in the header, I think at this point you need to look at other files as the likely culprit(s).
Please post the relevant section(s) of your main *.cpp file (or whatever you may have named it).
Edited
12 Years Ago
by Fbody because:
n/a
12 Years Ago
I don’t think the problem is with his header being included multiple times. It appears to me that the issue is that he is instantiating the player objects p1, p2, p3, etc. within the header file. It’s hard to tell without seeing the other files as well and what is included. I don’t see a “main”, so this is apparently not the only file in the program.
Maybe you could provide us with more details?
Moschops
683
Practically a Master Poster
Featured Poster
12 Years Ago
Instantiating objects in a header file isn’t forbidden, it’s just (very) bad practice and would only be a problem if the header were included multiple times. I wonder if there are error messages about redefinition of existing objects p1, p2, p3… as well, tucked away in the error messages list.
We certainly could do with seeing the rest of the code and all the error messages.
Edited
12 Years Ago
by Moschops because:
n/a
Ancient Dragon
5,243
Achieved Level 70
Team Colleague
Featured Poster
12 Years Ago
If the objects were instantiated in a header file and the header file included in two or more *.c or *.cpp files, then the linker would complain about duplicate declarations, not “redefinition of ‘class player'”. That’s why its more likely a problem with missing header guards, or the class is in fact declared multiple times in the same header and/or *.cpp file. Even lack of header guards would not be a problem is the header file is included only once in the same *.cpp file.
Edited
12 Years Ago
by Ancient Dragon because:
n/a
12 Years Ago
Agree, AD, but based on the snippet that was provided, it doesn’t give one a warm, fuzzy feeling. There is no way of being deterministic without seeing all the code.
12 Years Ago
I’ve got a board class in another file (board.cpp (is it correct to use .cpp files?))
And of course, that’s not called player.
So, I’ll put the Header Guareds in again and I’ll see if it works.
Thanxs,
jt
12 Years Ago
Now when I do it, it stops giving me the errors about defining the class multiple times.
However, it gives me errors about the instances being defined twice or “Multiple times” in the code… I definitely didn’t define it twice.
Another thing is that it mentions some things in the *.o files (for main.cpp, board.cpp, and player.cpp). Is that normal. I’ve never seen it before.
Fbody
682
Posting Maven
Featured Poster
12 Years Ago
If it’s throwing errors related to *.o files, they’re probably LINKER errors, not COMPILER errors, but we really can’t say.
You must post relevant code and error messages when requesting assistance. Without them, everything we post is educated guesses and conjecture. It may be close, or it may be “out in Left-Field”. Please post the details of the errors, and the relevant code.
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
I am new to C++ programming and have a compiler error that I can’t figure out. Any help would be appreciated.
Since I’m not sure what other info might be needed here goes: All three files are in the same folder and there aren’t other source or header files in that folder. Oddly enough if I comment out the #include «Entity.h» in the Entity.cpp file and reference the source in Main.cpp instead of Entity.h it compiles and runs fine. I’m coding on Code::Blocks and with the GCC Compiler. Thanks again for any help.
The implementation file ( Entity.cpp ) should not contain the class definition again. Instead, you write non-inline definitions («out of class»):
Also note that your Entity.h header depends on std::string which requires the #include header there, not just in the implementation file ( Entity.cpp ). There is no need to use this-> here nor some of the semicolons ( ; ).
That is because you can define functions inline in the class (instead of putting them in the implementation file). What you did is implement all of them in the class definition, and therefore you don’t need an implementation file anymore.
Профиль
Группа: Модератор
Сообщений: 5814
Регистрация: 28.8.2004
Где: страна тысячи озё р
В заголовочном файле a.h описывается структура point и объявляется функция func_a.
В заголовочном файле b.h включается заголовочный файл a.h и объявляется функция func_b.
В основном файле программы main.cpp подключаются заголовочные файлы a.h и b.h, в функции main() поочерёдно вызываются функции func_a, func_b, затем программа завершается.
Проблема:
Программа не компилируется. Компилятор выдаст ошибку, например так:
В этом, итоговом, коде присутствуют два определения struct point. Это и служит причиной выдачи ошибки компилятором.
Решение:
Использовать условные директивы компилятора #ifndef. #define. #endif.
Их также называют «стражами включения».
Идентификатором файла может быть любое правильной имя переменной в С/С++.
Однако, принято давать этим иденфикаторам имена, состоящие из больших букв латинского алфавита и подчёркиваний, логические связанные с именем файла.
К примеру, для файла abcd.h можно взять идентификаторы ABCD_H, FILE_ABCD_H, ABCD_H_INCLUDED
Важно: идентификаторы заголовочных файлов в пределах одной программы(одного проекта) должны быть разными, иначе Вы получите обратный результат(не множественное включения, а отсутствие включения).
Работа этих директив в данном случае заключается в том, что в первой строчке проверяется, не определено ли A_H_INCLUDED. Если определно, значит, содержимое данного файла уже было включено, и компилятору не надо обрабатывать содержимое файла повторно. Если же нет, то определяем A_H_INCLUDED и обрабатываем дальше заголовочный файл.
#ifndef A_H_INCLUDED // а здесь идентификатор уже определён
#define A_H_INCLUDED // поэтому эта и все остальные строки до #endif удаляются
Это и есть желаемый нами код.
Данное решение работает на всех известных компиляторах С/С++.
Замечания:
1. В данном примере файл b.h тоже желательно должен быть обрамлён.
2. Не начинайте имя идентификатора с подчёркивания, это крайне не рекомендуется стандартом С++.
Другие решения.
Некоторые компиляторы С/С++ предоставляют ещё одно решение проблемы.
Для этого необходимо включить в начало каждого заголовочного файла директиву
Данная директива имеет тот же эффект, что и вышеприведенное решение, но для её применения потребуется компилятор, поддерживающий это расширение. В число таких компиляторов входят: компилятор из MS Visual Studio (MSVC), компилятор g++ из GCC.
1. Публиковать ссылки на вскрытые компоненты
2. Обсуждать взлом компонентов и делиться вскрытыми компонентами
Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, JackYF, bsa.
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей) |
0 Пользователей: |
« Предыдущая тема | C/C++: Для новичков | Следующая тема » |
[ Время генерации скрипта: 0.0985 ] [ Использовано запросов: 21 ] [ GZIP включён ]
Источник
Single class has a Class Redefinition Error
I’m new to C++, and I’m having a problem with my class definitions in a header file. The code for the header file (Student.h) is:
4 Answers 4
You need header guards on that header file. It is presumably being included twice.
Modify the header, adding these lines to the beginning and end.
With these directives added, the compiler will ignore all contents of the header file if it has already been parsed.
Alternatively, while it is not standard C++, all major compilers will allow you to put a single
as the first line of the header to prevent it from being parsed multiple times.
as the first line of a header file, instead of the defines. Even if this is non-standard, it does avoid name clashes and can reduce compile time.
See the Wikipedia entry on include guards for a more extensive explanation of the problem and information on how to avoid it.
In short, there are two ways to do it
Version 1, #defined include guards
Usually the #define is called some variation of the file name since it has to be different in every include file.
Version 2, #pragma once
This pragma is (as most pragmas) not portable to all compilers, but some of the most important ones. It also has the advantage of not needing a manually assigned name.
Which you use is up to you, but you most likely have to pick one 🙂
Источник
C++ compile error: redefinition of ‘class::class’
I have added the errors within comment lines of the code for the highlighted lines by the compiler.
NOTE: #endif exists at the end of header file
All of the most popular questions about this error concluded that header guards were needed, although, there are guards already included in this code. I thought I was misunderstanding how to properly separate the initialization list between header and source files but when I commented that out it was still producing the same error.
2 Answers 2
Basically, it should look like this in your header:
You are getting redefinition errors ( which i think are linker errors, and not compile errors ) because Address::Address() and Address::Address(const string&, const string&, const string&, const string&, const string&) are already defined in the header file, and you define them again in the CPP file
To avoid that, you need to replace function definition by declarations in your header file, by replacing <> by ; in your header file, this way :
At the exception of inline and template functions, function declaration goes in header file, and definitions goes into the CPP file
Not the answer you’re looking for? Browse other questions tagged c++ class header-files or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
C++ Error message redefinition of functions
I am using two stacks to implement a queue class. My header file looks like:
And my cpp (implementation) file looks like:
(other functions omitted).
However, using Xcode 4.5, it keeps saying that my functions (MyQueue,
MyQueue, enqueue, peek, etc.) are redefined. Can anyone help me to clarify where have I redefined them?
4 Answers 4
You’re trying something which I really don’t like. It’s a pretence.
You are trying to pretend the template code can be split into header file and implementation file. But because it can’t you have to cheat by including the implementation file in the header file. It’s less confusing if you don’t cheat or pretend and just have one file, the header file, with everything in it.
The precise reason that you get a redefinition is that you are compiling your cpp file, which includes your header file, which includes your cpp file again. So the content of the cpp file gets compiled twice.
In C and C++, #include behaves like a copy and paste. Everytime you see
it should be treated as if you literally retyped the whole file in that one spot. So if you compile MyQueue.cpp, the preprocessor will prepend the contents of MyQueue.h, which itself tacks on a duplicate of MyQueue.cpp evidenced by
and then follows the native content of MyQueue.cpp.
inside MyQueue.h, is the same as if you had written one big file with the contents of MyQueue.h, MyQueue.cpp and MyQueue.cpp again. (with the include of stack in there as well of course) That is why the compiler complained about functions getting redefined.
The Duplicate inserted from the
might also contain the line
but I think the include guards (ifndef,endif) protected against a recursive expansion since that did not seem to be an issue.
I would like to point out that putting all the implementation code and declaration code in the same file for templates is not the only solution, as others suggest.
You just have to remember that templates are generated at compile time and include them wherever they are needed. Like Aaron has pointed out, you can even force generate a template for a specific type or function so it’s accessible to all units.
In this way, the definition of a function can be embedded in an arbitrary module and the rest of the modules won’t complain that a function isn’t defined.
It is a suitable alternative to storing large implementations in header files that must be pasted around just to refer to the type (or function signature). And it works absolutely fine, for years now.
So for example, when I am ready to compile my big program, I might have a file called structures.cpp that I designate to implement lots of small structures I use, as well as instantiate all the templates for my project.
to generate all the other definitions the rest of the project’s modules would need.
Источник
Adblock
detector