Error c2086 переопределение

Error C2086: char cmd[1024]: переопределение при пинге ресурса C++ Решение и ответ на вопрос 1245205

vip72

11 / 11 / 7

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

Сообщений: 180

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

1

21.08.2014, 02:11. Показов 5270. Ответов 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

2060 / 1592 / 679

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

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

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,180

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

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

I get the error C2086 from Visual Studio when trying to declare a variable in a name space, define it in one code file and access it in another code file.
When building with gcc (from codeblocks), the error is
(… == path on my harddisk):

…file_one.cpp|2|error: redefinition of ‘RecvVarProxyFn Skins::fnSequenceProxyFn’
…file_one.h|4|note: ‘RecvVarProxyFn Skins::fnSequenceProxyFn’ previously declared here

Even when deactivating (using //) the access line in main(), the error is the same.

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

Why do I get a redefinition error for my attempt to define the variable in a separate code file?

NOTE:
I am using visual studio 2015 Target Platform set to version 8.1
and Platform toolset set to v140.

  • Remove From My Forums
  • Question

  • 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

Answers

  • 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

    • Marked as answer by

      Tuesday, March 22, 2016 9:51 AM

  • Remove From My Forums
  • Question

  • 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

Answers

  • 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

    • Marked as answer by

      Tuesday, March 22, 2016 9:51 AM

  • Remove From My Forums
  • Question

  • Hi,

    I have put the following into my .h file.
    namespace MySpace
             {
                  bool started;
                  void Draw_screen(Form ^my_form);
                  . . .
             }

    As long as I only include functions it compiles fine.  But as soon as I try to put a variable into the definition I get errors
     error C2086: ‘bool MySpace::started’ : redefinition
     see declaration of ‘MySpace::started

    I am using Studio 2008 and it is a CLR form/application I am using.
    Since I am not even using the new variable at this stage I do not see why I can’t define it.

    Tks Zach.

Answers

  • Hi,

    This was solved, as the result of another thread.
    I had cyclic/recursive includes .    
    What I needed was forward declarations;

    eg

    Try like this

    // my_code.h

    namespace my_space
    {
       ref class Form1;  // forward declaration
    }

    namespace game_space
    {
      int var1;
    }

    // my_code.cpp

    #include «Form1.h»
    #include «my_code.h»

    //namespace gamespace implementation

    • Marked as answer by

      Monday, January 5, 2009 11:08 PM

Понравилась статья? Поделить с друзьями:
  • Error c2086 redefinition
  • Error c2084 функция int main void уже имеет текст реализации
  • Error c2082 переопределение формального параметра
  • Error c2078 слишком много инициализаторов
  • Error c2078 too many initializers