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++ | ||
|
C++ | ||
|
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
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:
|
|
This is what my files look like:
loadImages.h
|
|
loadImages.cpp
|
|
I think it has something to do with this
|
|
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.
|
|
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
|
|
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
|
|
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 задайте свой вопрос.