Содержание
- Ошибка компилятора C2143
- Error c2143 syntax error missing before constant
- Answered by:
- Question
- Error c2143 syntax error missing before constant
- Asked by:
- Question
- All replies
- Error c2143 syntax error missing before constant
Ошибка компилятора C2143
синтаксическая ошибка: отсутствует «token1» перед «token2»
Компилятор ожидал определенный маркер (т. е. элемент языка, отличный от пробела) и нашел вместо него другой маркер.
Проверьте справочник по языку C++ , чтобы определить, где код синтаксически неверен. Так как компилятор может сообщить об этой ошибке после обнаружения строки, которая вызывает проблему, проверьте несколько строк кода, предшествующих ошибке.
C2143 может возникать в разных ситуациях.
Это может произойти, когда за оператором, который может квалифицировать имя ( :: , -> и . ), должно следовать ключевое слово template , как показано в следующем примере:
По умолчанию В C++ предполагается, что Ty::PutFuncType это не шаблон, поэтому следующее интерпретируется как знак меньшего. Необходимо явно сообщить компилятору, что PutFuncType является шаблоном, чтобы он смог правильно проанализировать угловую скобку. Чтобы исправить эту ошибку, используйте ключевое template слово для имени зависимого типа, как показано ниже:
C2143 может возникать, если используется /clr и using директива имеет синтаксическую ошибку:
Это также может произойти при попытке скомпилировать файл исходного кода с помощью синтаксиса CLR без использования /clr:
Первый символ без пробелов, следующий за оператором if , должен быть левой скобкой. Компилятор не может перевести ничего другого:
C2143 может возникать, когда закрывающая фигурная скобка, круглые скобки или точка с запятой отсутствуют в строке, в которой обнаружена ошибка, или в одной из строк выше:
Или при наличии недопустимого тега в объявлении класса:
Или, если метка не присоединена к оператору. Если необходимо поместить метку сама по себе, например в конце составного оператора, прикрепите ее к оператору NULL:
Эта ошибка может возникать, когда выполняется неквалифицированный вызов типа в стандартной библиотеке C++:
Или отсутствует ключевое typename слово:
Или при попытке определить явное создание экземпляра:
В программе C переменные должны быть объявлены в начале функции и не могут быть объявлены после того, как функция выполнит инструкции, не являющиеся объявлениями.
Источник
Error c2143 syntax error missing before constant
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I am migrating my aaplication from VS2002 to VS2012. When i try to build one of my projects i am getting the following error:
Error 696 error C2143: syntax error : missing ‘;’ before ‘constant’ c:program filesmicrosoft sdkswindowsv7.1aincludewinuser.h 5341
Error 697 error C2059: syntax error : ‘constant’ c:program filesmicrosoft sdkswindowsv7.1aincludewinuser.h 5341
Error 698 error C2061: syntax error : identifier ‘LPINPUT’ c:program filesmicrosoft sdkswindowsv7.1aincludewinuser.h 5348
I have searched my code it is not using winuser.h anywhere. When I goto mentioned line number of winuser.h I find the following code:
typedef struct tagINPUT <
DWORD type;
union
<
MOUSEINPUT mi;
KEYBDINPUT ki;
HARDWAREINPUT hi;
>;
> INPUT, *PINPUT, FAR* LPINPUT; //line no. 5341
WINAPI
SendInput(
__in UINT cInputs, // number of input in the array
__in_ecount(cInputs) LPINPUT pInputs, // array of inputs //line no. 5348
__in int cbSize); // sizeof(INPUT)
What could be the problem? Any suggestions?
Источник
Error c2143 syntax error missing before constant
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Asked by:
Question
Ok.. so I decide to start learning some inteligence and start in Visual C++ latest down load, get the turorials suggested which are great and get cracking at it.
After the fourth lesson I get the following build error
c:program filesmicrosoft visual studio 9.0vcincludeistream(13) : error C2143: syntax error : missing ‘;’ before ‘namespace’
the only difference with the various lesson projects I have been working on is the actual code
after typing the attached code I am unable to build all previous project lessons, I did the whole reboot thing and still the same problem?
Go to the directory indicated in the error message:
c:program filesmicrosoft visual studio 9.0vcinclude
Open the file istream with an editor or viewer. (Notepad will do.)
Copy and paste the first 20 lines of that file into a post here.
I suspect that you have a missing semi-colon or closing brace in your stdafx.h header file. You should begin your search there.
Best Wishes,
-David Delaune
Quote>I suspect that you have a missing semi-colon or closing brace in your stdafx.h header file
Note that the OP said:
Quote>after typing the attached code I am unable to build all previous project lessons
I take this to mean that projects which previously built cleanly will no longer do so.
Since each project should have it’s own stdafx.h it seems unlikely that this is the
source of the problem.
Note that the error message says:
missing ‘;’ before ‘namespace’
and points to line 13 of the header istream.
I see no word «namespace» anywhere in the istream header of my installation.
Note that the error message says:
missing ‘;’ before ‘namespace’
and points to line 13 of the header istream.
I see no word «namespace» anywhere in the istream header of my installation.
Check your definition of _STD_BEGIN.
Best Wishes,
-David Delaune
Quote>Check your definition of _STD_BEGIN.
Will no-one rid me of these meddlesome macros?
Good catch. Thanks.
That is correct regarding all the previous compiled projects, I have attached the requested code
That looks kosher, so the problem is probably earlier.
Looking at the include chain from iostream, it pulls in istream which pulls in ostream
which pulls in ios which pulls in xlocnum which pulls in climits, etc. etc. Before that,
stdafx.h pulls in targetver.h etc. etc. All of the above are pulled in (at least a few
dozen files) before we reach line 13 of istream where the error occurs.
First, go to the Project Properties and under
Configuration Properties=>C/C++=>Advanced
set the field «Show Includes» to «Yes» then click on «Apply/OK».
Go to the output window, select all of the lines, copy to Windows clipboard
and paste here in a message.
Second, answer these questions:
(1) Did you give each project its own name, or did you use the same name for each
project?
(2) Click on the Build menu, then click on «Clean Solution». Rebuild. Does the
problem persist?
(3) If the problem is still there, go to the Project Properties and under
Configuration Properties=>C/C++=>Precompiled Headers
set «Create/Use Precompiled Header» to «Not Using Precompiled Headers»
then click on «Apply/OK». Rebuild. Does the problem persist?
Источник
Error c2143 syntax error missing before constant
can I add to the header
#include
using namespace std;
rather than add the std:: prefix?
In a header file, I’d refrain from using the using namespace std; simply because you may run into issue later on. If you plan on keeping this is a local code and you’ve already used the using namespace call, then yes, string would be fine.
Just trying to show you properly rather than poor techniques.
thank you — always better to learn correctly, I will make the change to std::
are these correct:
bool containsWordHelper(nodeT *w, string word)
bool containsWordHelper(nodeT *w, std::string word)
void add(string word);
void add(std::string word)
Minus the missing semicolons, they appear to be.
Also, if in doubt, it doesn’t hurt to try putting std:: in front of it. Compile before and after and see if you get errors the second time.
Of what type is Iterator? I don’t see a declaration of Iterator nor do I see a header that could potentially house the declaration.
I edited it out for the example code
#include «iterator.h» and a few other headers are under #define _lexicon_h
Then, something you omitted is the cause. Paste the Iterator implementation (without omitting anything) here. If it’s a big file, use http://www.pastebin.org/
I believe they meant they omitted the header files to reduce the size of the paste. If Iterator was defined elsewhere, then you need to know how, and how it can be used.
My response was in regards as to what was shown and since they accepted the answer, I assumed it was what they were looking for.
Iterator could have been misspelled and they could have been confused on the implementation of it.
Edit: Sorry Framework, I just found this, and it’s above my head. Maybe you can help a little more?
http://www.cplusplus.com/forum/beginner/73046/
making the change to std:: solved the linker errors but creates a new problem.
the current edit:
Iterator getWordIterator(); —> std::string::iterator getWordIterator();
now the compiler finds an issue with a mismatch between the declaration in the .h file and the call
error C2440: ‘initializing’ : cannot convert from ‘std::_String_iterator ‘ to ‘Iterator ‘
C2556: ‘Iterator Lexicon::getWordIterator(void)’ : overloaded function differs only by return type from ‘std::_String_iterator Lexicon::getWordIterator(void)’
error C2371: ‘Lexicon::getWordIterator’ : redefinition; different basic types
I did not post the entire code, just the header and the function the compiler found the error in
Источник
- Remove From My Forums
-
Question
-
Hi,
I am migrating my aaplication from VS2002 to VS2012. When i try to build one of my projects i am getting the following error:
Error 696 error C2143: syntax error : missing ‘;’ before ‘constant’ c:program filesmicrosoft sdkswindowsv7.1aincludewinuser.h 5341
Error 697 error C2059: syntax error : ‘constant’ c:program filesmicrosoft sdkswindowsv7.1aincludewinuser.h 5341
Error 698 error C2061: syntax error : identifier ‘LPINPUT’ c:program filesmicrosoft sdkswindowsv7.1aincludewinuser.h 5348
I have searched my code it is not using winuser.h anywhere. When I goto mentioned line number of winuser.h I find the following code:
<winuser.h>
typedef struct tagINPUT {
DWORD type;union
{
MOUSEINPUT mi;
KEYBDINPUT ki;
HARDWAREINPUT hi;
};
} INPUT, *PINPUT, FAR* LPINPUT; //line no. 5341WINAPI
SendInput(
__in UINT cInputs, // number of input in the array
__in_ecount(cInputs) LPINPUT pInputs, // array of inputs //line no. 5348
__in int cbSize); // sizeof(INPUT)What could be the problem? Any suggestions?
Thanks in advance
Sumit
Answers
-
Error 698 error C2061: syntax error : identifier ‘LPINPUT’ c:program filesmicrosoft sdkswindowsv7.1aincludewinuser.h 5348
I have searched my code it is not using winuser.h anywhere.
Not directly maybe, but it’s obviously being pulled in automatically by another header.
When you use #include <windows.h> it triggers a cascade of #includes of which winuser.h
is one. If you set the project property to «Show Includes» the compile will show all of
the includes being used in the Output Window of the build.Check the order of your #include statements carefully. What do you have before the
#include <windows.h>? Do you have one or more of your own headers? If so, try changing
the order of the #includes (be careful of precompiled headers).Are you using anything such as an #include or #define *before* windows.h which might be
defining LPINPUT?— Wayne
-
Proposed as answer by
Friday, November 15, 2013 9:43 PM
-
Marked as answer by
May Wang — MSFT
Thursday, November 21, 2013 3:09 AM
-
Proposed as answer by
Это ошибка синтаксиса. Связана она с отсутствием необходимых разделителей между элементами языка. Компилятор ожидает, что некоторые элементы языка появятся прежде или после других элементов. Если этого не происходит, то он выдаем ошибку. Будем пробовать ее получить. Пишем код:
#include "stdafx.h" int main(int argc, char* argv[]) { int x; int y; if (x<y) : // двоеточие здесь совсем не нужно { } }
Результат работы компилятора:
D:VСTestErrorTestError.cpp(10) : error C2143: syntax error : missing ';' before ':'
Второй наиболее частый вариант это забыть поставить «;» после объявления класса.
#include "stdafx.h" class CMy { } // забыли ";" class CMy2 { } int main(int argc, char* argv[]) { }
Опять та же ошибка.
D:VСTestErrorTestError.cpp(12) : error C2236: unexpected 'class' 'CMy2' D:VСTestErrorTestError.cpp(12) : error C2143: syntax error : missing ';' before '{'
Еще один вариант с лишней скобки:
#include "stdafx.h" int main(int argc, char* argv[]) { } // это лишнее return 0; }
Опять та же ошибка:
D:VСTestErrorTestError.cpp(11) : warning C4508: 'main' : function should return a value; 'void' return type assumed D:VСTestErrorTestError.cpp(12) : error C2143: syntax error : missing ';' before 'return'
Отсутствие закрывающей скобки может привести к такой же ошибке:
#include "stdafx.h" int main(int argc, char* argv[]) { for (int x=0;x<10;x++ // не хватает ")" { } return 0; }
Как видите это ошибка связанна с синтаксисом. Если она у Вас появляется внимательно просмотрите код на предмет соответствия требованиям C++ (лишние знаки, забытые
Omion 190 / 55 / 12 Регистрация: 19.05.2015 Сообщений: 351 |
||||
1 |
||||
06.09.2021, 02:10. Показов 1764. Ответов 17 Метки нет (Все метки)
Доброго времени суток всем.
я не вижу ошибку. помогите пожалуйста
0 |
249 / 183 / 46 Регистрация: 31.01.2021 Сообщений: 923 |
|
06.09.2021, 04:00 |
2 |
Определение функции в теле другой функции нехорошая затея для Си. В очень старом Си помоему такое встречал. closures — замыкание поддерживал GNU C. В c++11 появилась возможность нечто подобное делать с помощью лямбда. Добавлено через 11 минут
1 |
Алексей1153 фрилансер 4478 / 3988 / 870 Регистрация: 11.10.2019 Сообщений: 10,503 |
||||
06.09.2021, 07:25 |
3 |
|||
Сообщение было отмечено Omion как решение РешениеOmion,
1 |
Вездепух 10435 / 5704 / 1553 Регистрация: 18.10.2014 Сообщений: 14,098 |
|
06.09.2021, 10:57 |
4 |
я не вижу ошибку. Так а почему вы пытаетесь определить одну функцию внутри другой? В С такого нет.
char a[512]={}; В С такого нет.
gets(a); В С такого нет.
0 |
из племени тумба-юбма 2351 / 1694 / 390 Регистрация: 29.11.2015 Сообщений: 8,209 Записей в блоге: 14 |
|
06.09.2021, 12:14 |
5 |
gets(a); В С такого нет. Раньше была такая функция, потом отказались. The function provides no means to prevent buffer overflow of the destination array, given sufficiently long input string. std::gets was deprecated in C++11 and removed from C++14.
0 |
Вездепух 10435 / 5704 / 1553 Регистрация: 18.10.2014 Сообщений: 14,098 |
|
06.09.2021, 12:33 |
6 |
Цитата об изменениях в стандарте С++ не уместна в форуме по С. the function has been deprecated in the third corrigendum to the C99 standard and removed altogether in the C11 standard.
1 |
фрилансер 4478 / 3988 / 870 Регистрация: 11.10.2019 Сообщений: 10,503 |
|
06.09.2021, 14:18 |
7 |
{} тут ноль пропустил, вот так вроде можно в Си P.S. компилил onlinegdb.com с выбором «C» по gets — предупреждение Видимо, компилятор там не совсем по стандартам
0 |
из племени тумба-юбма 2351 / 1694 / 390 Регистрация: 29.11.2015 Сообщений: 8,209 Записей в блоге: 14 |
|
06.09.2021, 15:10 |
8 |
Цитата об изменениях в стандарте С++ не уместна в форуме по С. Все верно, вечно лезу в С++. А какой тогда последний стандарт для Си?
0 |
249 / 183 / 46 Регистрация: 31.01.2021 Сообщений: 923 |
|
06.09.2021, 15:16 |
9 |
мама Стифлера,
0 |
Модератор 11659 / 7172 / 1704 Регистрация: 25.07.2009 Сообщений: 13,142 |
|
06.09.2021, 16:43 |
10 |
Так а почему вы пытаетесь определить одну функцию внутри другой? В С такого нет. Точнее это расширение gcc. Стандартом не является, как следствие, майкрософтовским cl (судя по виду ошибки) не компилируется.
#include <conio.h>
В С такого нет. По крайней мере в стандартном.
the function has been deprecated in the third corrigendum to the C99 standard and removed altogether in the C11 standard.
Если компилятору ставить команду (-std=c11), получается компилятор будет пропускать данную функцию. У меня он даже с std=c17 пропускает. Матерится, на чём свет стоит, но пропускает… Код andrew@itandrew:~/prog/c/other$ gcc -Wall in_func.c in_func.c: In function ‘test’: in_func.c:7:9: warning: implicit declaration of function ‘gets’; did you mean ‘fgets’? [-Wimplicit-function-declaration] 7 | gets(a); | ^~~~ | fgets /usr/bin/ld: /tmp/ccncVxbg.o: в функции «test.2495»: in_func.c:(.text+0x31): предупреждение: the `gets' function is dangerous and should not be used. andrew@itandrew:~/prog/c/other$ ./a.out blah blah blah 14 simbols blah blah blah andrew@itandrew:~/prog/c/other$ gcc -Wall -std=c17 in_func.c in_func.c: In function ‘test’: in_func.c:7:9: warning: implicit declaration of function ‘gets’; did you mean ‘fgets’? [-Wimplicit-function-declaration] 7 | gets(a); | ^~~~ | fgets /usr/bin/ld: /tmp/cc4yPDRd.o: в функции «test.2085»: in_func.c:(.text+0x31): предупреждение: the `gets' function is dangerous and should not be used.
0 |
Вездепух 10435 / 5704 / 1553 Регистрация: 18.10.2014 Сообщений: 14,098 |
|
06.09.2021, 23:38 |
11 |
У меня он даже с std=c17 пропускает. Любая ругань компилятора должна анализироваться на предмет того, является ли она требуемым стандартом языка диагностическим сообщением или просто невинной вольностью компилятора. В данном случае вы получили именно стандартные диагностические сообщения. Это значит, что код не компилируется, т.е. «НЕ пропускает». С точки зрения стандартного языка С, любые результаты компиляции (выполнимые файлы и т.п.) в такой ситуации являются просто непредсказуемым «мусором», который компилятор забыл убрать за собой. Такой анализ диагностические сообщений вы должны либо делать сами, глазами, на основе вашего знания стандарта языка, либо вы можете попросить компилятор GCC делать это за вас (в меру его способностей) путем указания ключа
1 |
190 / 55 / 12 Регистрация: 19.05.2015 Сообщений: 351 |
|
07.09.2021, 17:35 [ТС] |
12 |
TheCalligrapher,
Раньше была такая функция, потом отказались. читаю доки тут, чуть ниже крутнуть и вот она. На самом деле меня тоже удивило что она описана в доках и при этом ide подсвечивает красным, типо файл не подключен. Хотя работает.
По крайней мере в стандартном. В конце параграфа, назовем это параграфом, «Как вводить и выводить информацию» описано подключение заголовка conio.h стандарт
0 |
Вездепух 10435 / 5704 / 1553 Регистрация: 18.10.2014 Сообщений: 14,098 |
|
07.09.2021, 18:34 |
13 |
TheCalligrapher, Перечитал несколько раз, но так и не понял, что именно вы хотели сказать.
читаю доки тут, чуть ниже крутнуть и вот она. Это не «доки», а реферат на вольную тему на основе материалов уровня «это было давно и неправда» и «полная чушь». (Просмотрел еще раз). Нет, это дичь невероятная.
0 |
из племени тумба-юбма 2351 / 1694 / 390 Регистрация: 29.11.2015 Сообщений: 8,209 Записей в блоге: 14 |
|
07.09.2021, 18:44 |
14 |
Omion, почитайте про функцию gets(): здесь и здесь, думаю поймете сами. Добавлено через 3 минуты
-pedantic-errors Странно, у меня не выдает даже предупреждения. Вот все ключи которые ставлю: (-static-libgcc -Wfloat-equal -Werror=vla -std=c11 -Wall -Wextra -pedantic-errors -s) Кликните здесь для просмотра всего текста Код Compiling single file... -------- - Filename: C:UsersAspireM3400Desktopforum1.c - Compiler Name: TDM-GCC 9.2.0 Processing C source file... -------- - C Compiler: C:TDM_GCC_920bingcc.exe - Command: gcc.exe "C:UsersAspireM3400Desktopforum1.c" -o "C:UsersAspireM3400Desktopforum1.exe" -I"C:TDM_GCC_920include" -I"C:TDM_GCC_920x86_64-w64-mingw32include" -I"C:TDM_GCC_920libgccx86_64-w64-mingw329.2.0include" -L"C:TDM_GCC_920lib" -L"C:TDM_GCC_920x86_64-w64-mingw32lib" -static-libgcc -Wfloat-equal -Werror=vla -std=c11 -Wall -Wextra -pedantic-errors -s Compilation results... -------- - Errors: 0 - Warnings: 0 - Output Filename: C:UsersAspireM3400Desktopforum1.exe - Output Size: 17.5 KiB - Compilation Time: 0.47s
0 |
Модератор 11659 / 7172 / 1704 Регистрация: 25.07.2009 Сообщений: 13,142 |
|
07.09.2021, 19:05 |
15 |
Такой анализ диагностические сообщений вы должны либо делать сами, глазами, на основе вашего знания стандарта языка Здесь все, кто хоть раз собирал ядро FreeBSD, перекрестились…
либо вы можете попросить компилятор GCC делать это за вас (в меру его способностей) путем указания ключа -pedantic-errors. Вот с этим соглашусь. Для начинающих это крайне полезная опция, прямо необходимая.
С точки зрения стандартного языка С, любые результаты компиляции (выполнимые файлы и т.п.) в такой ситуации являются просто непредсказуемым «мусором», который компилятор забыл убрать за собой. Да и с этим не спорю, кроме разве-что последней фразы. Компилятор забыл — лирика какая-то. Компилятор сделал, что просили, но предупредил, что используется опасная функция. Хотя по логике должен бы выдать сообщение, что такой функции просто нет, раз уж её из стандарта исключили.
Доки где читаю Это не стандарт, стандарт здесь, и никакого conio.h в нём нет! Это происки мелкомягких, не более того. Добавлено через 8 минут
Странно, у меня не выдает даже предупреждения. Действительно странно.
Хотя по логике должен бы выдать сообщение, что такой функции просто нет, раз уж её из стандарта исключили. Вообще-то компилятор именно это и сказал, предупредил линковщик, тут я погорячился, gcc — лучший!
0 |
Вездепух 10435 / 5704 / 1553 Регистрация: 18.10.2014 Сообщений: 14,098 |
|
07.09.2021, 19:32 |
16 |
Здесь все, кто хоть раз собирал ядро FreeBSD, перекрестились…
Да и с этим не спорю, кроме разве-что последней фразы. Компилятор забыл — лирика какая-то. Компилятор сделал, что просили, но предупредил, что используется опасная функция. Подход, описанный мною выше, касается именно тех случаев, когда мы сознательно хотим смотрет на код через ежовые очки педантичного стандартного С. Речи совсем не идет о том, чтобы постоянно придерживаться такой суровой педантичности в реальной жизни. Моя «лирика» приведена лишь для того, чтобы заметить, что такое поведение компилятора формально не является «багом» компилятора.
Хотя по логике должен бы выдать сообщение, что такой функции просто нет, раз уж её из стандарта исключили. Так ведь на самом деле именно это он и сказал здесь Код warning: implicit declaration of function ‘gets’ точно так же вы можете вызвать функцию А то, что эта ошибка рапортуется как «implicit declaration», говорит о том, что ваш компилятор, выдав требуемое стандартом диагностическое сообщение, не прерывает трансляцию, а пытается выпутаться из ситуации местодами C89/90. Имеет право.
0 |
Модератор 11659 / 7172 / 1704 Регистрация: 25.07.2009 Сообщений: 13,142 |
|
07.09.2021, 19:41 |
17 |
-pedantic-errors пресекла бы эти попытки. Больше того! Она и объявление одной функции внутри другой не пропустит!
0 |
Вездепух 10435 / 5704 / 1553 Регистрация: 18.10.2014 Сообщений: 14,098 |
|
07.09.2021, 19:44 |
18 |
Странно, у меня не выдает даже предупреждения. Вот все ключи которые ставлю: (-static-libgcc -Wfloat-equal -Werror=vla -std=c11 -Wall -Wextra -pedantic-errors -s) У меня в cygwin тоже. Это скорее всего какая-то особенность портов стандартной библиотеки для Windows, в которых gcc упорно отказывается удалять
1 |
did anyone ever got this case ??
it’s driving me crazy , can’t understand where is the error !!
first I thought it could be in the header file <queue> , I checked it , no ‘;’ is missing
#ifndef _ERRLIST_H_ #define _ERRLIST_H_ #include <queue> #include <string> struct errorStruct{ int errLineNum; int errColNum ; string errMessage; }; queue <errorstruct> errQueue; //error points here class ErrList { public: void pushError(int line,int col,string message); void popError(); void printErrors(); int getSize(); }; #endif </errorstruct></string></queue>
Solution 1
I see two problems:
First you define queue<errorstruct>
instead of queue<errorStruct>
Secondly, string and queue are in the std namespace. Write std::string
and std::queue
instead.
Comments
Solution 2
Like mcbain said the error you are getting is a non descriptive one from the compiler. It basically means the compiler cannot locate any class / struct or declaration by the name of queue, thus it is expecting it to be a variable which should be followed by a ;.
You could fix this by adding
#using std;
Or like mcbain suggested by adding std:: before the usage of the queue type (std::queue.
Comments
Solution 3
I had the similar issue what I found was that my header files contains cyclic reference. For instance I have a base class like below:
#include "OtherClass.h" class BaseClass { protected: OtherClass* otherClass; }
In OtherClass.h, I was referencing «BaseClass.h» file that was causing the issue.
Hope that might help you.
Thanks,
Muhammad Masood
[blog link removed]
Comments
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
Top Experts | |
Last 24hrs | This month |
CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900
- Forum
- Beginners
- error C2143: syntax error : missing ‘;’
error C2143: syntax error : missing ‘;’ before ‘<‘
error C2143: syntax error : missing ‘;’ before ‘<‘
error C4430: missing type specifier — int assumed. Note: C++ does not support default-int
error C2238: unexpected token(s) preceding ‘;’
|
|
Was this maybe what you were looking for?
std::string::iterator getWordIterator();
can I add to the header
#include <string>
using namespace std;
rather than add the std:: prefix?
In a header file, I’d refrain from using the using namespace std;
simply because you may run into issue later on. If you plan on keeping this is a local code and you’ve already used the using namespace call, then yes, string would be fine.
Just trying to show you properly rather than poor techniques.
thank you — always better to learn correctly, I will make the change to std::
are these correct:
bool containsWordHelper(nodeT *w, string word)
bool containsWordHelper(nodeT *w, std::string word)
void add(string word);
void add(std::string word)
Minus the missing semicolons, they appear to be.
Also, if in doubt, it doesn’t hurt to try putting std:: in front of it. Compile before and after and see if you get errors the second time.
Of what type is
Iterator
? I don’t see a declaration of
Iterator
nor do I see a header that could potentially house the declaration.
Wazzak
Last edited on
I edited it out for the example code
#include «iterator.h» and a few other headers are under #define _lexicon_h
Then, something you omitted is the cause. Paste the
Iterator
implementation (without omitting anything) here. If it’s a big file, use http://www.pastebin.org/
Wazzak
Last edited on
I believe they meant they omitted the header files to reduce the size of the paste. If Iterator was defined elsewhere, then you need to know how, and how it can be used.
My response was in regards as to what was shown and since they accepted the answer, I assumed it was what they were looking for.
Iterator could have been misspelled and they could have been confused on the implementation of it.
Edit: Sorry Framework, I just found this, and it’s above my head. Maybe you can help a little more?
http://www.cplusplus.com/forum/beginner/73046/
Last edited on
making the change to std:: solved the linker errors but creates a new problem.
the current edit:
Iterator<string> getWordIterator(); —> std::string::iterator getWordIterator();
now the compiler finds an issue with a mismatch between the declaration in the .h file and the call
|
|
error C2440: ‘initializing’ : cannot convert from ‘std::_String_iterator<_Elem,_Traits,_Alloc>’ to ‘Iterator<ElemType>’
|
|
C2556: ‘Iterator<ElemType> Lexicon::getWordIterator(void)’ : overloaded function differs only by return type from ‘std::_String_iterator<_Elem,_Traits,_Alloc> Lexicon::getWordIterator(void)’
error C2371: ‘Lexicon::getWordIterator’ : redefinition; different basic types
I did not post the entire code, just the header and the function the compiler found the error in
I am going to revert the edit and try another path to a solution. The Iterator<string> getWordIterator(); compiled in a previous working version so i know it works. And, the edit created the template mismatch errors. I ma going to focus on the Linker errors and check the source files.
Topic archived. No new replies allowed.
saddam alshloul
October 8, 2012 at 10:12 pm
guyzzz i did it like this
// Day10Doc.h : interface of the CDay10Doc class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_DAY10DOC_H__A12642CF_7E96_4273_B3B5_FA94CD497BEC__INCLUDED_)
#define AFX_DAY10DOC_H__A12642CF_7E96_4273_B3B5_FA94CD497BEC__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CLine;
class CDay10Doc : public CDocument
{
protected: // create from serialization only
CDay10Doc();
DECLARE_DYNCREATE(CDay10Doc)
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CDay10Doc)
public:
virtual BOOL OnNewDocument();
virtual void Serialize(CArchive& ar);
//}}AFX_VIRTUAL
// Implementation
public:
int GetLineCount();
CLine* AddLine(CPoint ptFrom, CPoint ptTo);
CObArray m_oaLines;
virtual ~CDay10Doc();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(CDay10Doc)
// NOTE – the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_DAY10DOC_H__A12642CF_7E96_4273_B3B5_FA94CD497BEC__INCLUDED_)
and that works good, thanx alot but after compiling i got another errors not in Day10.cpp file but in Day10View.cpp file
for Day10View the code is:
// Day10View.cpp : implementation of the CDay10View class
//
#include “stdafx.h”
#include “Day10.h”
#include “Day10Doc.h”
#include “Day10View.h”
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CDay10View
IMPLEMENT_DYNCREATE(CDay10View, CView)
BEGIN_MESSAGE_MAP(CDay10View, CView)
//{{AFX_MSG_MAP(CDay10View)
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
ON_WM_MOUSEMOVE()
//}}AFX_MSG_MAP
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDay10View construction/destruction
CDay10View::CDay10View()
{
// TODO: add construction code here
}
CDay10View::~CDay10View()
{
}
BOOL CDay10View::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CView::PreCreateWindow(cs);
}
/////////////////////////////////////////////////////////////////////////////
// CDay10View drawing
void CDay10View::OnDraw(CDC* pDC)
{
CDay10Doc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
///////////////////////
// MY CODE STARTS HERE
///////////////////////
// Get the number of lines in the document
int liCount = pDoc->GetLineCount();
// Are there any lines in the document?
if (liCount)
{
int liPos;
CLine*lptLine;
// Loop through the lines in the document
for (liPos = 0; liPos GetLine(liPos);
// Draw the line
lptLine->Draw(pDC);
}
}
///////////////////////
// MY CODE ENDS HERE
///////////////////////
}
/////////////////////////////////////////////////////////////////////////////
// CDay10View printing
BOOL CDay10View::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CDay10View::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void CDay10View::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
/////////////////////////////////////////////////////////////////////////////
// CDay10View diagnostics
#ifdef _DEBUG
void CDay10View::AssertValid() const
{
CView::AssertValid();
}
void CDay10View::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CDay10Doc* CDay10View::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CDay10Doc)));
return (CDay10Doc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CDay10View message handlers
void CDay10View::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
CView::OnLButtonDown(nFlags, point);
}
void CDay10View::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
///////////////////////
// MY CODE STARTS HERE
///////////////////////
// Capture the mouse, so no other application can
// grab it if the mouse leaves the window area
SetCapture();
// Save the point
m_ptPrevPos = point;
///////////////////////
// MY CODE ENDS HERE
///////////////////////
CView::OnLButtonDown(nFlags, point);
}
void CDay10View::OnLButtonUp(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
///////////////////////
// MY CODE STARTS HERE
///////////////////////
// Have we captured the mouse?
if (GetCapture() == this)
// If so, release it so other applications can
// have it
ReleaseCapture();
///////////////////////
// MY CODE ENDS HERE
///////////////////////
CView::OnLButtonUp(nFlags, point);
}
void CDay10View::OnMouseMove(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
///////////////////////
// MY CODE STARTS HERE
///////////////////////
// Check to see if the left mouse button is down
if ((nFlags & MK_LBUTTON) == MK_LBUTTON)
{
// Have we captured the mouse?
if (GetCapture() == this)
{
// Get the Device Context
CClientDC dc(this);
// Add the line to the document
CLine *pLine = GetDocument()->AddLine(m_ptPrevPos, point);
// Draw the current stretch of line
pLine->Draw(&dc);
// Save the current point as the previous point
m_ptPrevPos = point;
}
}
///////////////////////
// MY CODE ENDS HERE
///////////////////////
CView::OnMouseMove(nFlags, point);
}
and the errors i got are:
——————-Configuration: Day10 – Win32 Debug——————–
Compiling…
Day10.cpp
Day10View.cpp
D:VC++6MSDev98MyProjectsDay10Day10View.cpp(76) : error C2039: ‘GetLine’ : is not a member of ‘CDay10Doc’
d:vc++6msdev98myprojectsday10day10doc.h(13) : see declaration of ‘CDay10Doc’
D:VC++6MSDev98MyProjectsDay10Day10View.cpp(78) : error C2027: use of undefined type ‘CLine’
d:vc++6msdev98myprojectsday10day10doc.h(12) : see declaration of ‘CLine’
D:VC++6MSDev98MyProjectsDay10Day10View.cpp(78) : error C2227: left of ‘->Draw’ must point to class/struct/union
D:VC++6MSDev98MyProjectsDay10Day10View.cpp(138) : error C2084: function ‘void __thiscall CDay10View::OnLButtonDown(unsigned int,class CPoint)’ already has a body
D:VC++6MSDev98MyProjectsDay10Day10View.cpp(188) : error C2027: use of undefined type ‘CLine’
d:vc++6msdev98myprojectsday10day10doc.h(12) : see declaration of ‘CLine’
D:VC++6MSDev98MyProjectsDay10Day10View.cpp(188) : error C2227: left of ‘->Draw’ must point to class/struct/union
Generating Code…
Compiling…
Day10Doc.cpp
Generating Code…
Error executing cl.exe.
Day10.exe – 6 error(s), 0 warning(s)