C2086 c ошибка

У меня есть некоторые проблемы с моим кодом C ++. Я пытаюсь теперь разделить заголовочный файл, который содержит определения и объявления некоторых указателей на символы (ранее строки, но у меня были некоторые проблемы с CRT, поэтому я изменил их на указатель на символ). Так как я изменил их на указатель на символ, я получаю ошибки переопределения.

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>";
};
};

На самом деле не знаю, что я делаю здесь не так …

Это ошибка, которую я получаю:

Ошибка 2 ошибка C2086: ‘const char * DataVerifier :: Structure :: strHTMLTemplate’: переопределение c: \ users \ suzan \ documents \ visual studio 2013 \ projects \ test1 \ test1 \ testconstantsheader.cpp 7 1 Test1
Ошибка 3 ошибка C2086: ‘const char * DataVerifier :: Structure :: strHTMLTemplate’: переопределение c: \ users \ suzan \ documents \ visual studio 2013 \ projects \ test1 \ test1 \ testconstantsheader.cpp 7 1 Test1

0

Решение

Ваш заголовочный файл содержит определение объекта strHTMLTemplate с внешней связью. Это то, что приводит к множественной ошибке определения.

Изменить определение strHTMLTemplate в заголовочном файле в не определяющая декларация добавив ключевое слово extern

// TestConstantsHeader.h

namespace DataVerifier
{
namespace Structure
{
extern const char *strHTMLTemplate;
}
}

Кроме того, вероятно, имеет смысл объявить указатель как const char *const strHTMLTemplate, Это не похоже, что это должно быть изменяемым.

3

Другие решения

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:\users\suzan\documents\visual studio 2013\projects\test1\test1\testconstantsheader.cpp 7 1 Test1
Error 3 error C2086: ‘const char *DataVerifier::Structure::strHTMLTemplate’ : redefinition c:\users\suzan\documents\visual studio 2013\projects\test1\test1\testconstantsheader.cpp 7 1 Test1

Перейти к контенту

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C2086

Compiler Error C2086

11/04/2016

C2086

C2086

4329bf72-90c8-444c-8524-4ef75e6b2139

Compiler Error C2086

‘identifier’ : redefinition

The identifier is defined more than once, or a subsequent declaration differs from a previous one.

C2086 can also be the result of incremental building for a referenced C# assembly. Rebuild the C# assembly to resolve this error.

The following sample generates C2086:

// C2086.cpp
main() {
  int a;
  int a;   // C2086 not an error in ANSI C
}

vip72

11 / 11 / 7

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

Сообщений: 180

Записей в блоге: 1

1

21.08.2014, 02:11. Показов 5480. Ответов 3

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Хочу программу заделать чтобы нагрузить немного свой сайт (в коде на примере гугла)

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
 
int main()
{
    char cmd[1024];
    sprintf (cmd,"ping google.com -t -l 10000");
    int exit_status = system(cmd);
    char cmd[1024];
    sprintf (cmd,"ping google.com -t -l 10000");
    int bexit_status = system(cmd);
    char cmd[1024];
    sprintf (cmd,"ping google.com -t -l 10000");
    int aexit_status = system(cmd);
    return 0;
}

То есть я одновременно пытаюсь запустить проверку пинга у гугла 3 раза, обычно это делают запустив 3 раза отдельно командную строку и запуская проверку, а я хочу одновременно в одной

Лог:

1>—— Построение начато: проект: lol2, Конфигурация: Debug Win32 ——
1>Компиляция…
1>main.cpp
1>c:usersasusdocumentsvisual studio 2008projectslol2lol2main.cpp(7) : warning C4996: ‘sprintf’: This function or variable may be unsafe. Consider using sprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
1> c:program files (x86)microsoft visual studio 9.0vcincludestdio.h(366): см. объявление ‘sprintf’
1>c:usersasusdocumentsvisual studio 2008projectslol2lol2main.cpp(9) : error C2086: char cmd[1024]: переопределение
1> c:usersasusdocumentsvisual studio 2008projectslol2lol2main.cpp(6): см. объявление ‘cmd’
1>c:usersasusdocumentsvisual studio 2008projectslol2lol2main.cpp(12) : error C2086: char cmd[1024]: переопределение
1> c:usersasusdocumentsvisual studio 2008projectslol2lol2main.cpp(6): см. объявление ‘cmd’
1>Журнал построения был сохранен в «file://c:UsersasusDocumentsVisual Studio 2008Projectslol2lol2DebugBuildLog.htm»
1>lol2 — ошибок 2, предупреждений 1
========== Построение: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========

0

John Prick

2102 / 1622 / 691

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

Сообщений: 4,859

21.08.2014, 02:22

2

C++
1
2
3
4
5
6
7
8
9
int main()
{
    char cmd[1024];
//...
    char cmd[1024];
//...
    char cmd[1024];
//...
}

Три раза объявляешь один и тот же массив. Либо сделай разные массивы (cmd1, cmd2 …), либо убери эти повторные объявления.

1

vip72

11 / 11 / 7

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

Сообщений: 180

Записей в блоге: 1

21.08.2014, 03:06

 [ТС]

3

Как-то так чтоли:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
 
int main()
{
    char cmd[1024];
    sprintf (cmd,"ping google.com -t -l 10000");
system(cmd);
    char cmd[1024];
    sprintf (cmd,"ping google.com -t -l 10000");
system(cmd);
    char cmd[1024];
    srintf (cmd,"ping google.com -t -l 10000");
    system(cmd);
    return 0;
}

Всё равно те же ошибки, напишите пожалуйста рабочий код, я просто новичек

Добавлено через 35 минут
Как бы получилось, но вроде как по отдельности пингует:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;
 
int main()
{
    char cmd[1024];
    sprintf_s (cmd,"ping google.com -n 5");
    system(cmd);
    char cmd1[2048];
    sprintf_s (cmd,"ping google.com -n 6");
    system(cmd1);
    char cmd2[2048];
    sprintf_s (cmd,"ping google.com -n 7");
    system(cmd2);
    system("pause");
    return 0;
}

Первый пропингует а потом 2 ошибк подряд что слишком длинная входная строка, а надо одновременно пинговать

0

КОП

1123 / 794 / 219

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

Сообщений: 2,183

21.08.2014, 06:33

4

Цитата
Сообщение от vip72
Посмотреть сообщение

sprintf_s (cmd,»ping google.com -n 6″);
* * system(cmd1);

для начала неплохо бы исправить cmd на cmd1 и cmd2 соответственно

Добавлено через 1 час 13 минут
И что значит одновременно? Какой смысл в три потока пинговать один сервер?

так пойдет?

C++
1
2
3
ShellExecute(NULL, NULL, L"C:\Windows\System32\ping", L"google.com -n 5", NULL, SW_NORMAL);
    ShellExecute(NULL, NULL, L"C:\Windows\System32\ping", L"google.com -n 6", NULL, SW_NORMAL);
    ShellExecute(NULL, NULL, L"C:\Windows\System32\ping", L"google.com -n 7", NULL, SW_NORMAL);

Добавлено через 1 час 43 минуты
пардон, отвлекся, забыл, что цель — нагрузка сервера. Тогда можно все в 1 консоли, но мусора там будет…

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
#include "stdafx.h"
#include <iostream>
#include <windows.h>
 
using namespace std;
 
//===========================================================================
//---------------------------------------------------------------------------
 
void Thread1()
{
    system("C:\Windows\System32\ping google.com -n 5");
}
 
 
int main()
{
    int n;
    cin >> n; //кол-во потоков
    for (int i = 0; i < n; i++)
    CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)Thread1, NULL, 0, 0);
 
    system("pause");
    return 0;
}

1

У меня есть некоторые проблемы с моим кодом C ++. Я пытаюсь теперь разделить заголовочный файл, который содержит определения и объявления некоторых указателей на символы (ранее строки, но у меня были некоторые проблемы с CRT, поэтому я изменил их на указатель на символ). Так как я изменил их на указатель на символ, я получаю ошибки переопределения.

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>";
};
};

На самом деле не знаю, что я делаю здесь не так …

Это ошибка, которую я получаю:

Ошибка 2 ошибка C2086: ‘const char * DataVerifier :: Structure :: strHTMLTemplate’: переопределение c: users suzan documents visual studio 2013 projects test1 test1 testconstantsheader.cpp 7 1 Test1
Ошибка 3 ошибка C2086: ‘const char * DataVerifier :: Structure :: strHTMLTemplate’: переопределение c: users suzan documents visual studio 2013 projects test1 test1 testconstantsheader.cpp 7 1 Test1

0

Решение

Ваш заголовочный файл содержит определение объекта strHTMLTemplate с внешней связью. Это то, что приводит к множественной ошибке определения.

Изменить определение strHTMLTemplate в заголовочном файле в не определяющая декларация добавив ключевое слово extern

// TestConstantsHeader.h

namespace DataVerifier
{
namespace Structure
{
extern const char *strHTMLTemplate;
}
}

Кроме того, вероятно, имеет смысл объявить указатель как const char *const strHTMLTemplate, Это не похоже, что это должно быть изменяемым.

3

Другие решения

  • 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

Вопрос

Это мой CPP-код:

#include <iostream>
#include <string>
#include <array>
#include <cmath>
using namespace std;
/*
bool func1(int budget){
    if( budget < 0 ) {
        cout << "Budget cannot be negative."<< endl; 
        return false; 
    }
    else {
        return true; 
    }
}
bool func2(int num1, int num2, int num3){ 
    if (int num1 < 0 || int num2 < 0 || int num3 < 0 ) {
        cout << "All quantities must be positive."<< endl;
        return false;
    }
    else { 
        return true;
    }
}
*/
int func3(int *p, int index){
    
    int currentprice = *(p) * 5 + *(p+1) * 10 + *(p+2) * 15  ;
    return currentprice; 

}









int manin() {
    int budget;
    int num1, num2, num3;
    int p1;
    int p2;
    int p3;
    int currentprice;
    int func3;
    cin >> p1 >> p2 >> p3 ;
    int position[3] ;
    position[0] = p1 ; 
    position[1] = p2 ; 
    position[2] = p3 ; 
    int *p;
    p= position;
    int func3(currentprice);
    cout << currentprice;
return 0; 
}

Это ошибка, которую я получаю :

1>------ Build started: Project: ConsoleApplication3, Configuration: Debug Win32 ------
1>  Source.cpp
1>c:usersnonameonedrivemasaüstücsconsoleapplication3consoleapplication3source.cpp(56): error C2086: 'int func3' : redefinition
1>          c:usersnonameonedrivemasaüstücsconsoleapplication3consoleapplication3source.cpp(48) : see declaration of 'func3'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

пожалуйста, не могли бы вы помочь мне с мастерами CPP?

3

Полезно начинать с определенной цели. Что вы пытаетесь сделать, не очень понятно.

int func3(int *p, int index) является функцией и int func3 является переменной величиной. Вот в чем заключается ваша ошибка. Вы можете переименовать переменную, чтобы избежать этой ошибки.

Кроме того, это неправильный способ вызова функции: int func3(currentprice);. Во-первых, эта функция принимает два параметра вместо одного. Во-вторых, возвращаемое значение нигде не хранится.

Кроме того, консольная программа начнет выполняться с main функция. Так manin вероятно, должно быть main.

Этот…

    int func3;

… является декларацией о func3 в качестве переменной типа int. Он затеняет объявление функции в области действия файла func3().

Этот…

    int func3(currentprice);

также является декларацией о func3 (не вызов функции) из-за int спереди. Вы не можете повторно объявлять локальную переменную func3 в одной и той же области, даже если два объявления обозначают один и тот же тип.

Удалите int func3; в целом. Также удалите int От int func3(currentprice);.



@JohnBollinger @DKS @JohnnyMopp @DrewDormann @ThomasMatthews
Ребята, я исправил это с помощью ваших предложений, это приводит к успеху. Тем не менее, это должно занять 3 cin(p1,p2,p3) и должно указывать на текущую цену, вместо этого она показывает пустое значение.
Я добавляю новые коды ниже:

#include <iostream>
#include <string>
#include <array>
#include <cmath>
using namespace std;
/*
bool func1(int budget){
    if( budget < 0 ) {
        cout << "Budget cannot be negative."<< endl; 
        return false; 
    }
    else {
        return true; 
    }
}
bool func2(int num1, int num2, int num3){ 
    if (int num1 < 0 || int num2 < 0 || int num3 < 0 ) {
        cout << "All quantities must be positive."<< endl;
        return false;
    }
    else { 
        return true;
    }
}
*/
int func3(int *p){
    
    int currentprice = *(p) * 5 + *(p+1) * 10 + *(p+2) * 15  ;
    return  currentprice; 

}









int main() {
    /*
    int budget;
    int num1, num2, num3;
    */
    int p1;
    int p2;
    int p3;
    int currentprice= 0;
    cin >> p1 >> p2 >> p3 ;
    int position[3] ;
    position[0] = p1 ; 
    position[1] = p2 ; 
    position[2] = p3 ; 
    int *p;
    p= position;
    func3(p);
    cout << currentprice;
return 0; 
}

На других языках

Эта страница на других языках

empty row

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

Популярное в этой категории

Популярные вопросы в этой категории

Обновлено

Вопрос:

Я получаю ошибку C2086 из Visual Studio при попытке объявить переменную в пространстве имен, определить ее в одном файле кода и получить к ней доступ в другом файле кода.
При создании с помощью gcc (из кодовых блоков) ошибка (… == путь на моем жестком диске):

… file_one.cpp | 2 | ошибка: переопределение “RecvVarProxyFn Skins :: fnSequenceProxyFn”
… file_one.h | 4 | note: ‘RecvVarProxyFn Skins :: fnSequenceProxyFn’, ранее объявленный здесь

Даже при деактивации (используя //) линии доступа в main() ошибка одинакова.

file_one.h:

typedef int RecvVarProxyFn;

namespace Skins {
RecvVarProxyFn fnSequenceProxyFn; // "previously declared here"
}

file_one.cpp

#include "file_one.h"
RecvVarProxyFn Skins::fnSequenceProxyFn = 0; // redefinition error 2086

main.cpp

#include "file_one.h"
int main()
{   Skins::fnSequenceProxyFn = 1; // making this a comment does not help
return 0;
}

Почему я получаю ошибку переопределения для моей попытки определить переменную в отдельном файле кода?

НОТА:
Я использую visual studio 2015 Target Platform для версии 8.1
и набор инструментов платформы, установленный в v140.

Лучший ответ:

Используйте ключевое слово extern для изменения одного из определений в декларации.
Очевидно, что строка в заголовке является первым выбором.

namespace Skins {
    extern RecvVarProxyFn fnSequenceProxyFn;
}

Вопрос

Это мой CPP-код:

#include <iostream>
#include <string>
#include <array>
#include <cmath>
using namespace std;
/*
bool func1(int budget){
    if( budget < 0 ) {
        cout << "Budget cannot be negative."<< endl; 
        return false; 
    }
    else {
        return true; 
    }
}
bool func2(int num1, int num2, int num3){ 
    if (int num1 < 0 || int num2 < 0 || int num3 < 0 ) {
        cout << "All quantities must be positive."<< endl;
        return false;
    }
    else { 
        return true;
    }
}
*/
int func3(int *p, int index){
    
    int currentprice = *(p) * 5 + *(p+1) * 10 + *(p+2) * 15  ;
    return currentprice; 

}









int manin() {
    int budget;
    int num1, num2, num3;
    int p1;
    int p2;
    int p3;
    int currentprice;
    int func3;
    cin >> p1 >> p2 >> p3 ;
    int position[3] ;
    position[0] = p1 ; 
    position[1] = p2 ; 
    position[2] = p3 ; 
    int *p;
    p= position;
    int func3(currentprice);
    cout << currentprice;
return 0; 
}

Это ошибка, которую я получаю :

1>------ Build started: Project: ConsoleApplication3, Configuration: Debug Win32 ------
1>  Source.cpp
1>c:\users\noname\onedrive\masaüstü\cs\consoleapplication3\consoleapplication3\source.cpp(56): error C2086: 'int func3' : redefinition
1>          c:\users\noname\onedrive\masaüstü\cs\consoleapplication3\consoleapplication3\source.cpp(48) : see declaration of 'func3'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

пожалуйста, не могли бы вы помочь мне с мастерами CPP?

3

Полезно начинать с определенной цели. Что вы пытаетесь сделать, не очень понятно.

int func3(int *p, int index) является функцией и int func3 является переменной величиной. Вот в чем заключается ваша ошибка. Вы можете переименовать переменную, чтобы избежать этой ошибки.

Кроме того, это неправильный способ вызова функции: int func3(currentprice);. Во-первых, эта функция принимает два параметра вместо одного. Во-вторых, возвращаемое значение нигде не хранится.

Кроме того, консольная программа начнет выполняться с main функция. Так manin вероятно, должно быть main.

Этот…

    int func3;

… является декларацией о func3 в качестве переменной типа int. Он затеняет объявление функции в области действия файла func3().

Этот…

    int func3(currentprice);

также является декларацией о func3 (не вызов функции) из-за int спереди. Вы не можете повторно объявлять локальную переменную func3 в одной и той же области, даже если два объявления обозначают один и тот же тип.

Удалите int func3; в целом. Также удалите int От int func3(currentprice);.



@JohnBollinger @DKS @JohnnyMopp @DrewDormann @ThomasMatthews
Ребята, я исправил это с помощью ваших предложений, это приводит к успеху. Тем не менее, это должно занять 3 cin(p1,p2,p3) и должно указывать на текущую цену, вместо этого она показывает пустое значение.
Я добавляю новые коды ниже:

#include <iostream>
#include <string>
#include <array>
#include <cmath>
using namespace std;
/*
bool func1(int budget){
    if( budget < 0 ) {
        cout << "Budget cannot be negative."<< endl; 
        return false; 
    }
    else {
        return true; 
    }
}
bool func2(int num1, int num2, int num3){ 
    if (int num1 < 0 || int num2 < 0 || int num3 < 0 ) {
        cout << "All quantities must be positive."<< endl;
        return false;
    }
    else { 
        return true;
    }
}
*/
int func3(int *p){
    
    int currentprice = *(p) * 5 + *(p+1) * 10 + *(p+2) * 15  ;
    return  currentprice; 

}









int main() {
    /*
    int budget;
    int num1, num2, num3;
    */
    int p1;
    int p2;
    int p3;
    int currentprice= 0;
    cin >> p1 >> p2 >> p3 ;
    int position[3] ;
    position[0] = p1 ; 
    position[1] = p2 ; 
    position[2] = p3 ; 
    int *p;
    p= position;
    func3(p);
    cout << currentprice;
return 0; 
}

На других языках

Эта страница на других языках

empty row

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

……………………………………………………………………………………………………

Популярное в этой категории

Популярные вопросы в этой категории

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • C2131 ошибка kia rio
  • C2131 ошибка hyundai solaris
  • C2014 ошибка мазда
  • C2131 ошибка hyundai ix35
  • C2013 mazda ошибка

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: