Error c2086 redefinition

I'm having some issues with my C++ code. I'm trying to now split a header file which has definitions and declarations of some char pointers (previously strings but i've been having some CRT issues so

I’m having some issues with my C++ code. I’m trying to now split a header file which has definitions and declarations of some char pointers (previously strings but i’ve been having some CRT issues so changing them to a char pointer). Since I’ve changed them to a char pointer, i’m getting redefinition errors.

Test.h

#pragma once
#define DllExport   __declspec( dllexport )

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
#include <stdexcept>
#include "TestConstantsHeader.cpp"

namespace DataVerifier
{
    class DllExport CDataVerifier
    {
    public:
        CDataVerifier();
        ~CDataVerifier();

        //! @brief A function that processes the messages
        void Process();
    };
}

Test.cpp

#include "Test.h"

using namespace DataVerifier;

CDataVerifier::CDataVerifier()
{
}

CDataVerifier::~CDataVerifier(){}

void CDataVerifier::Process()
{
    const char* strTmp = Structure::strHTMLTemplate;
    strTmp = "hello";
    std::cout << strTmp;
}

TestConstantsHeader.h

#pragma once
#define DllExport   __declspec( dllexport )

#include <iostream>

namespace DataVerifier
{
    namespace Structure
    {
        const char *strHTMLTemplate;/* = "<doctype html>"
            "<html lang="en">"
            "<head>"
            "<meta charset="utf-8"/>"
            "<title>Data Verifier Test Results - {@testdesc}</title>"
            "<style>"
            "body {"
            "tbackground: none repeat scroll 0 0 #F3F3F4;"
            "tcolor: #1E1E1F;"
            "tfont-family: "Segoe UI",Tahoma,Geneva,Verdana,sans-serif;"
            "tmargin: 0;"
            "tpadding: 0;"
            "}"
            "h1 {"
            "tbackground-color: #E2E2E2;"
            "tborder-bottom: 1px solid #C1C1C2;"
            "tcolor: #201F20;"
            "tfont-size: 21pt;"
            "tfont-weight: normal;"
            "tmargin: 0;"
            "tpadding: 10px 0 10px 10px;"
            "}"
            "h2 {"
            "tfont-size: 18pt;"
            "tfont-weight: normal;"
            "tmargin: 0;"
            "tpadding: 15px 0 5px;"
            "}"
            "h3 {"
            "tbackground-color: rgba(0, 0, 0, 0);"
            "tfont-size: 15pt;"
            "tfont-weight: normal;"
            "tmargin: 0;"
            "tpadding: 15px 0 5px;"
            "}"
            "a {"
            "tcolor: #1382CE;"
            "}"
            "table {"
            "tborder-collapse: collapse;"
            "tborder-spacing: 0;"
            "tfont-size: 10pt;"
            "}"
            "table th {"
            "tbackground: none repeat scroll 0 0 #E7E7E8;"
            "tfont-weight: normal;"
            "tpadding: 3px 6px;"
            "ttext-align: left;"
            "ttext-decoration: none;"
            "}"
            "table td {"
            "tbackground: none repeat scroll 0 0 #F7F7F8;"
            "tborder: 1px solid #E7E7E8;"
            "tmargin: 0;"
            "tpadding: 3px 6px 5px 5px;"
            "tvertical-align: top;"
            "}"
            ""
            ".textCentered {"
            "ttext-align: center;"
            "}"
            ".messageCell {"
            "twidth: 100;"
            "}"
            "#content {"
            "tpadding: 0 12px 12px;"
            "}"
            "#overview table {"
            "tmax-width: 75;"
            "twidth: auto;"
            "}"
            "#messages table {"
            "twidth: 97;"
            "}"
            "</style>"
            "</head>"
            "<body>"
            "<div id="big_wrapper">"
            "t<h1>Test Results - {@testdesc}</h1>"
            "t<table>"
            "{@eeddata}"
            "t</table>"
            "</body>"
            "</html>";*/
    }
}

TestConstantsHeader.cpp

#include "TestConstantsHeader.h"

namespace DataVerifier
{
    namespace Structure
    {
        const char *strHTMLTemplate = "<doctype html>"
            "<html lang="en">"
            "<head>"
            "<meta charset="utf-8"/>"
            "<title>Data Verifier Test Results - {@testdesc}</title>"
            "<style>"
            "body {"
            "tbackground: none repeat scroll 0 0 #F3F3F4;"
            "tcolor: #1E1E1F;"
            "tfont-family: "Segoe UI",Tahoma,Geneva,Verdana,sans-serif;"
            "tmargin: 0;"
            "tpadding: 0;"
            "}"
            "h1 {"
            "tbackground-color: #E2E2E2;"
            "tborder-bottom: 1px solid #C1C1C2;"
            "tcolor: #201F20;"
            "tfont-size: 21pt;"
            "tfont-weight: normal;"
            "tmargin: 0;"
            "tpadding: 10px 0 10px 10px;"
            "}"
            "h2 {"
            "tfont-size: 18pt;"
            "tfont-weight: normal;"
            "tmargin: 0;"
            "tpadding: 15px 0 5px;"
            "}"
            "h3 {"
            "tbackground-color: rgba(0, 0, 0, 0);"
            "tfont-size: 15pt;"
            "tfont-weight: normal;"
            "tmargin: 0;"
            "tpadding: 15px 0 5px;"
            "}"
            "a {"
            "tcolor: #1382CE;"
            "}"
            "table {"
            "tborder-collapse: collapse;"
            "tborder-spacing: 0;"
            "tfont-size: 10pt;"
            "}"
            "table th {"
            "tbackground: none repeat scroll 0 0 #E7E7E8;"
            "tfont-weight: normal;"
            "tpadding: 3px 6px;"
            "ttext-align: left;"
            "ttext-decoration: none;"
            "}"
            "table td {"
            "tbackground: none repeat scroll 0 0 #F7F7F8;"
            "tborder: 1px solid #E7E7E8;"
            "tmargin: 0;"
            "tpadding: 3px 6px 5px 5px;"
            "tvertical-align: top;"
            "}"
            ""
            ".textCentered {"
            "ttext-align: center;"
            "}"
            ".messageCell {"
            "twidth: 100;"
            "}"
            "#content {"
            "tpadding: 0 12px 12px;"
            "}"
            "#overview table {"
            "tmax-width: 75;"
            "twidth: auto;"
            "}"
            "#messages table {"
            "twidth: 97;"
            "}"
            "</style>"
            "</head>"
            "<body>"
            "<div id="big_wrapper">"
            "t<h1>Test Results - {@testdesc}</h1>"
            "t<table>"
            "{@eeddata}"
            "t</table>"
            "</body>"
            "</html>";
    };
};

Really don’t know what I’m doing wrong here…

This is the error i’m getting:

Error 2 error C2086: ‘const char *DataVerifier::Structure::strHTMLTemplate’ : redefinition c:userssuzandocumentsvisual studio 2013projectstest1test1testconstantsheader.cpp 7 1 Test1
Error 3 error C2086: ‘const char *DataVerifier::Structure::strHTMLTemplate’ : redefinition c:userssuzandocumentsvisual studio 2013projectstest1test1testconstantsheader.cpp 7 1 Test1

  • Remove From My Forums
  • Вопрос

  • Hello,

    I added my header file in MyProject.cpp as

    #include "MyProject.h"

    But when I go to add my int definition into MyProject.h

    Visual Studio does not compile and shows:

    Error  1	error C2086: 'int users' : redefinition

    In MyProject.cpp, variable users is declared as:

    int users = 245;

    So why I am getting this error and how can I fix it?

    Strangely this issue only happens for int variables?
    Function
    definitions do not create any issue in header file for compilation?

    Cheers

Ответы

  • Do like this

    MyProject.h file
    
    #pragma once
    
    extern int users;  // declaration
    
    wchar_t *subStr(wchar_t *string, int position, int length);
    
    MyProject.cpp file
    
    int users = 1;   // definition
    
    wchar_t *subStr(wchar_t *string, int position, int length)
    {
      return string + position; // or other definition
    }
    

    Only put declarations in header files, not definitions.


    David Wilkinson | Visual C++ MVP

    • Помечено в качестве ответа

      22 марта 2016 г. 9:51

36 / 0 / 1

Регистрация: 18.03.2015

Сообщений: 162

1

05.05.2022, 09:22. Показов 1317. Ответов 6


Есть такие вот хедер и файл реализации.
Почему-то при компиляции студия ругается: SCamera camera: переопределение, хотя в main.cpp и в других файлах нет определения этой структуры…

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
AMERA_H_INCLUDED
#define CAMERA_H_INCLUDED
 
struct SCamera {
    float x, y, z;
    float Xrot, Zrot;
} camera;
 
void Camera_apply();
void Camera_Rotation(float xAngle, float zAngle);
void Camera_AutoMoveByMouse(int centerX, int centerY, float speed);
void Camera_MoveDirection(int forvardMove, int rightMove, int speed);
#endif CAMERA_H_INCLUDED
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <windows.h>
#include <glad/glad.h>
#include <camera.h>
#include <math.h>
 
struct SCamera camera = { 0,0,1.7, 0,0 };
 
void Camera_apply() {
    glRotatef(-camera.Xrot, 1, 0, 0);
    glRotatef(-camera.Zrot, 0, 0, 1);
    glTranslatef(-camera.x, -camera.y, -camera.z);
}
 
void Camera_Rotation(float xAngle, float zAngle) {
 
    camera.Zrot += zAngle;
    if (camera.Zrot < 0) camera.Zrot += 360;
    if (camera.Zrot > 360) camera.Zrot -= 360;
    camera.Xrot += xAngle;
    if (camera.Xrot < 0) camera.Xrot += 0;
    if (camera.Xrot > 180) camera.Xrot -= 180;
}
 
void Camera_AutoMoveByMouse(int centerX, int centerY, float speed) {
 
    POINT cur;
    POINT base = { centerX,centerY };
    GetCursorPos(&cur);
    Camera_Rotation((base.y - cur.y) * speed, (base.x - cur.x) * speed);
    SetCursorPos(base.x, base.y);
}
 
void Camera_MoveDirection(int forvardMove, int rightMove, int speed) {
 
    float ugol = camera.Zrot / 180 * 3.14159265358979323846;
 
    if (forvardMove > 0)
        ugol += rightMove > 0 ? 0.785398163397448309616 : (rightMove < 0 ? -0.785398163397448309616 : 0);
    if (forvardMove < 0)
        ugol += 3.14159265358979323846 + (rightMove > 0 ? -0.785398163397448309616 : (rightMove < 0 ? 0.785398163397448309616 : 0));
    if (forvardMove == 0)
        ugol += rightMove > 0 ? 1.57079632679489661923 : 1.57079632679489661923;
    if (rightMove == 0) speed = 0;
 
    if (speed != 0) {
        camera.x += sin(ugol) * speed;
        camera.y += cos(ugol) * speed;
    }
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



  • Forum
  • Beginners
  • redefining

redefining

Hello,

I’m trying to get my .cpp files to interact with eachother using .h files. But everytime I try to compile it it says the variables are already defined in the header file.

I get these errors:

1
2
3
4
5
6
c:usersgebruikerdesktopgrid controlgrid controlgrid controlloadimages.cpp(37): error C2086: 'SDL_Surface *horStripeImage' : redefinition
1>          c:usersgebruikerdesktopgrid controlgrid controlgrid controlloadimages.h(6) : see declaration of 'horStripeImage'
1>c:usersgebruikerdesktopgrid controlgrid controlgrid controlloadimages.cpp(38): error C2086: 'SDL_Surface *verStripeImage' : redefinition
1>          c:usersgebruikerdesktopgrid controlgrid controlgrid controlloadimages.h(7) : see declaration of 'verStripeImage'
1>c:usersgebruikerdesktopgrid controlgrid controlgrid controlloadimages.cpp(39): error C2086: 'SDL_Surface *playfieldImage' : redefinition
1>          c:usersgebruikerdesktopgrid controlgrid controlgrid controlloadimages.h(8) : see declaration of 'playfieldImage'

This is what my files look like:

loadImages.h

1
2
3
4
5
6
7
8
9
10
#ifndef LOADIMAGES_H_GUARD
#define LOADIMAGES_H_GUARD

#include "SDL.h"

SDL_Surface* horStripeImage;
SDL_Surface* verStripeImage;
SDL_Surface* playfieldImage;

#endif 

loadImages.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include "loadImages.h"

//Load stripe_horizontal.bmp
SDL_Surface* loadHorStripe()
{
	SDL_Surface* loadedImage = SDL_LoadBMP( "stripe_horizontal.bmp" );
	SDL_Surface* stripe_horizontal = SDL_DisplayFormat( loadedImage );

	SDL_FreeSurface( loadedImage );

	return stripe_horizontal;
}

//Load stripe_vertical.bmp
SDL_Surface* loadVerStripe()
{
	SDL_Surface* loadedImage = SDL_LoadBMP( "stripe_vertical.bmp" );
	SDL_Surface* stripe_vertical = SDL_DisplayFormat( loadedImage );

	SDL_FreeSurface( loadedImage );

	return stripe_vertical;
}

//Load playfield.bmp
SDL_Surface* loadPlayfield()
{
	SDL_Surface* loadedImage = SDL_LoadBMP( "playfield.bmp" );
	SDL_Surface* playfield = SDL_DisplayFormat( loadedImage );

	SDL_FreeSurface( loadedImage );

	return playfield;
}

//Assign variables
SDL_Surface* horStripeImage = loadHorStripe();
SDL_Surface* verStripeImage = loadVerStripe();
SDL_Surface* playfieldImage = loadPlayfield();

I think it has something to do with this

1
2
3
4
//Assign variables
SDL_Surface* horStripeImage = loadHorStripe();
SDL_Surface* verStripeImage = loadVerStripe();
SDL_Surface* playfieldImage = loadPlayfield();

but I don’t know what to do. Please help me.

Thanks in advance.

In the header file you should declare variables, not define them. (Hence the redefinition error.)

You declare by using the

extern

keyword.

1
2
3
4
5
6
7
8
9
10
#ifndef LOADIMAGES_H_GUARD
#define LOADIMAGES_H_GUARD

#include "SDL.h"

extern SDL_Surface* horStripeImage;
extern SDL_Surface* verStripeImage;
extern SDL_Surface* playfieldImage;

#endif  

You can declare a variable/function many times, but there has to be only one definition. You have re-defined the variables in loadImages.cpp. Although i would use extern just as Catfish proposed, it’s considered redundant in C++.

Although i would use extern just as Catfish proposed, it’s considered redundant in C++.

How so? If you want to access a global variable defined in a source file, you will need to declare it as extern somewhere — best bet is the header file of that source file.

Although i would use extern just as Catfish proposed, it’s considered redundant in C++.

I’ll bite. For what reason is it considered redundant in C++?

@cire
I’ll bite. For what reason is it considered redundant in C++?

For the same error as in the original post.:)

@cire, this is linked to the OP’s example (again), but the following

1
2
3
 
extern int x = 3; 
int x = 3; 

are essentially equivalent, so had Staygold defined the images the first way, he could have just dropped the extern. Do note that it is not my personal opinion, but rather what i’ve read in «The C++ Programming Language» not too long ago. Apart from the
cases in which you have to use extern as Catfish mentioned, it also conveys your intents better and makes them explicit.

Last edited on

@cire, this is linked to the OP’s example (again), but the following

1
2
extern int x = 3; 
int x = 3; 

re essentially equivalent, so had Staygold defined the images the first way, he could have just dropped the extern.

You responded to and referenced Catfish’s post, where extern was required and far from redundant. If the OP had moved the initialization and definition of the variables to the header file as you seem to be suggesting, he would’ve had redefinitions of the variables in multiple source files. I don’t see your point.

According to the C++ Standard

2 A declaration is a definition unless … it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a function body,

Last edited on

Extern solved the problem. Thanks alot.

Topic archived. No new replies allowed.

Я решил эту проблему (из здесь). Просто разместите его здесь, чтобы любой, кто столкнется с ошибкой, нашел более понятный вопрос и ответ, чем копаться на веб-сайте, откуда я его взял. Я сам скоро отвечу на этот вопрос.

Обнаруженные ошибки:

Error 13 error C2086: 'int APIENTRY' : redefinition C:Program FilesMicrosoft Visual Studio 8VCPlatformSDKincludeGLgl.h 1153  
Error 10 error C2086: 'int WINGDIAPI' : redefinition C:Program FilesMicrosoft Visual Studio 8VCPlatformSDKincludeGLgl.h 1153   
Error 3 error C2144: syntax error : 'void' should be preceded by ';' C:Program FilesMicrosoft Visual Studio 10VCincludeGLgl.h 1152 

5 ответы

Решение: [Получено из этот сайт]

Вам нужно добавить WIN32 к определениям в вашем проекте. В Visual Studio щелкните проект правой кнопкой мыши, выберите C/C++, препроцессор и в поле «Определения препроцессора» добавьте WIN32 для конфигураций отладки и выпуска. Пока вы это делаете, также добавьте _DEBUG для конфигурации отладки и NDEBUG для конфигурации выпуска…
По какой-то причине проекты VS по умолчанию не имеют определений препроцессора, хотя их, по крайней мере, следует использовать почти всегда…

Мое решение уже содержало эти определения препроцессора. MSDN предлагает вам также добавить #include <windows.h>

Создан 28 янв.

У меня был фрагмент кода, ищущий _WIN32, а не просто WIN32.

Что бы это ни стоило, популярная звуковая библиотека использует это перед включением windows.h:

#if defined(_WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64)
#include <windows.h>
#endif

Создан 02 янв.

Я также хочу добавить решение CMake.

Вы должны добавить /D «WIN32» к CMAKE_CXX_FLAGS, который можно найти в расширенных записях.

Создан 06 ноя.

Недавно я столкнулся с этим с пустым проектом, использующим Visual C++ 2019.

Что сработало для меня, так это определить _WINDOWS как директиву препроцессора вместо WIN32.

Создан 05 ноя.

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

visual-studio-2010
build
openscenegraph

or задайте свой вопрос.

Понравилась статья? Поделить с друзьями:
  • Error c2065 undeclared identifier error c2065 undeclared identifier
  • Error c2065 string необъявленный идентификатор
  • Error c2065 null необъявленный идентификатор
  • Error c2065 func undeclared identifier
  • Error c2065 cout необъявленный идентификатор