I am new to programming C.. please tell me what is wrong with this program, and why I am getting this error: error C2143: syntax error : missing ‘;’ before ‘type’….
extern void func();
int main(int argc, char ** argv){
func();
int i=1;
for(;i<=5; i++) {
register int number = 7;
printf("number is %dn", number++);
}
getch();
}
asked Mar 29, 2013 at 4:10
8
Visual Studio only supports C89. That means that all of your variables must be declared before anything else at the top of a function.
EDIT: @KeithThompson prodded me to add a more technically accurate description (and really just correct where mine is not in one regard). All declarations (of variables or of anything else) must precede all statements within a block.
answered Mar 29, 2013 at 4:17
Ed S.Ed S.
122k21 gold badges181 silver badges262 bronze badges
2
I haven’t used visual in at least 8 years, but it seems that Visual’s limited C compiler support does not allow mixed code and variables. Is the line of the error on the declaration for int i=1;
?? Try moving it above the call to func();
Also, I would use extern void func(void);
answered Mar 29, 2013 at 4:18
Randy HowardRandy Howard
2,16015 silver badges26 bronze badges
this:
int i=1;
for(;i<=5; i++) {
should be idiomatically written as:
for(int i=1; i<=5; i++) {
because there no point to declare for
loop variable in the function scope.
answered Mar 29, 2013 at 4:17
leniklenik
23k4 gold badges32 silver badges43 bronze badges
8
Содержание
- Ошибка компилятора C2143
- Strange syntax error C2143 in Visual only (missing ‘;’ before ‘type’)
- 2 Answers 2
- error C2143 : missing ‘;’ before ‘*’
- 3 Answers 3
- error C2143: syntax error : missing ‘;’ before ‘type’ [closed]
- 1 Answer 1
- Compiler Error C2143 when using a struct
- 5 Answers 5
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
Ошибка компилятора C2143
синтаксическая ошибка: отсутствует «token1» перед «token2»
Компилятор ожидал определенный маркер (т. е. элемент языка, отличный от пробела) и нашел вместо него другой маркер.
Проверьте справочник по языку C++ , чтобы определить, где код синтаксически неверен. Так как компилятор может сообщить об этой ошибке после обнаружения строки, которая вызывает проблему, проверьте несколько строк кода, предшествующих ошибке.
C2143 может возникать в разных ситуациях.
Это может произойти, когда за оператором, который может квалифицировать имя ( :: , -> и . ), должно следовать ключевое слово template , как показано в следующем примере:
По умолчанию В C++ предполагается, что Ty::PutFuncType это не шаблон, поэтому следующее интерпретируется как знак меньшего. Необходимо явно сообщить компилятору, что PutFuncType является шаблоном, чтобы он смог правильно проанализировать угловую скобку. Чтобы исправить эту ошибку, используйте ключевое template слово для имени зависимого типа, как показано ниже:
C2143 может возникать, если используется /clr и using директива имеет синтаксическую ошибку:
Это также может произойти при попытке скомпилировать файл исходного кода с помощью синтаксиса CLR без использования /clr:
Первый символ без пробелов, следующий за оператором if , должен быть левой скобкой. Компилятор не может перевести ничего другого:
C2143 может возникать, когда закрывающая фигурная скобка, круглые скобки или точка с запятой отсутствуют в строке, в которой обнаружена ошибка, или в одной из строк выше:
Или при наличии недопустимого тега в объявлении класса:
Или, если метка не присоединена к оператору. Если необходимо поместить метку сама по себе, например в конце составного оператора, прикрепите ее к оператору NULL:
Эта ошибка может возникать, когда выполняется неквалифицированный вызов типа в стандартной библиотеке C++:
Или отсутствует ключевое typename слово:
Или при попытке определить явное создание экземпляра:
В программе C переменные должны быть объявлены в начале функции и не могут быть объявлены после того, как функция выполнит инструкции, не являющиеся объявлениями.
Источник
Strange syntax error C2143 in Visual only (missing ‘;’ before ‘type’)
I’m getting a strange compilation error for a C code in MSVC only. More precisely:
error C2143: syntax error : missing ‘;’ before ‘type’
C2143 is a fairly generic error, and there are myriad of questions on SO around it, but none of them seems to apply so far. The closest one can be found here, and stress the importance of declaring variables at the beginning of a block, which seems to have been respected here.
Here is a sample code:
The following code works well:
This one doesn’t:
The second code works well with GCC, so the issue seems restricted to MSVC. My understanding is that macro ALLOCATE_ONSTACK() only do variable declaration and initialization, so it seems to respect C syntax.
2 Answers 2
OK, this one is fairly convoluted.
It ends with a ; character.
Now look at your code :
It also ends with a ‘;’ character. That means that, on this particular line, you have 2 following ‘;’ characters.
Since MSVC is not C99, it requires all declarations to be done at the beginning of the block. Since you have two ‘;’ characters following each other, it acts as if the declaration area was ended. So, when you declare other variables in :
it then fails, syntax error.
GCC has no such problem since it is C99.
Either remove the ‘;’ character at the end of the macro, or within your source code. Only one is required. Not sure which solution is better.
[Edit] : As suggested in comments and other answer, removing the semicolon from the macro looks the better solution.
Источник
error C2143 : missing ‘;’ before ‘*’
hello I have searched everywhere on the internet for an answer but i can’t find any.
How do I fix this?
3 Answers 3
The problem in this case appears to be that Sprite is not recognized as a type. After a better look, the problem you have is that you define:
in both files. You do that in the .cpp file(or Game.h file.. first code snippet) and you also do it in the Sprite.h file. The problem is that at the time that the compiler goes to Sprite.h GAME_H is already defined and therefore, thanks to the #ifndef routine it no longer compiles the Sprite.h file.
To fix it change in the Sprite.h file like so:
I’m guessing that this is from the compile of Sprite.cpp.
Sprite.cpp includes sprite.h, which includes game.h at the top. The latter include includes sprite.h again, which does nothing due to its inclusion guard or pragma once. That means, that at that point there is no known class called sprite — as in this compilation, it’s below it.
Resulting code (after preprocessing, before compiling) would look like:
In essence, you can’t fix this easily. You would need to make one of the headers not depend on the other being included first. You can do that by, every time you don’t need the contents of the class, to forward declare it instead of including it.
so if you do this and then compile sprite.cpp, the preprocessed output is going to look like
which will work. The compiler doesn’t need to know what Sprite is exactly at the time you declare a pointer to it. In fact, the only times you do need the full declaration is when:
- You use members of the class
- You inherit from the class
- You use sizeof on the class
- You instantiate a template with it
And that’s about it. There may be more but they won’t be common cases and you shouldn’t run into them that quickly. In any case, use a forward declaration first and if that really doesn’t work, then include the header.
Источник
error C2143: syntax error : missing ‘;’ before ‘type’ [closed]
Closed 6 years ago .
Now, this code is not mine. The code belongs to the Chowdren Clickteam Compiler.
Now. I’ve been trying to fix this but the developer has been very busy. Now, I don’t know C but I know a lot on Python and since this File is not Python. I can’t fix it correctly. I’ve been getting a syntax error.
Now the compiler I’m using is so people will stop extracting my source code for my games. Now, here is the code. Any help will be GREAT.
Line 178 and 184 are the ones that are breaking.
^^^ Thoses are the ones that are breaking.
I posted the void thingy below with the two broken lines.
1 Answer 1
It looks like you are using an older version of Visual C which does not support C99. You need to use a more modern compiler, either a current/recent version of Visual C, or ideally gcc, clang, or any modern C99-compliant compiler.
Alternatively if you are for some unfortunate reason stuck with your old version of Visual C then you could fix all such variable definitions to make them C89-compliant (i.e. move them to the start of an enclosing block).
The specific problem you are seeing is that variables are declared in the middle of a code block, rather than at the start — this has been allowed since C99 (and earlier, as an extension in compilers such as gcc). Microsoft has only recently caught up (more or less) with C99.
To fix the specific function which you are having problems with:
Источник
Compiler Error C2143 when using a struct
I’m compiling a simple .c in visual c++ with Compile as C Code (/TC) and i get this compiler error
error C2143: syntax error : missing ‘;’ before ‘type’
on a line that calls for a simple struct
same goes for using the typedef of the struct.
error C2275: ‘FOO’ : illegal use of this type as an expression
5 Answers 5
I forgot that in C you have to declare all your variables before any code.
Did you accidentally omit a semicolon on a previous line? If the previous line is an #include , you might have to look elsewhere for the missing semicolon.
Edit: If the rest of your code is valid C++, then there probably isn’t enough information to determine what the problem is. Perhaps you could post your code to a pastebin so we can see the whole thing.
Ideally, in the process of making it smaller to post, it will suddenly start working and you’ll then have discovered the problem!
Because you’ve already made a typedef for the struct (because you used the ‘s1’ version), you should write:
That will work in both C and C++
How is your structure type defined? There are two ways to do it:
C2143 basically says that the compiler got a token that it thinks is illegal in the current context. One of the implications of this error is that the actual problem may exist before the line that triggers the compiler error. As Greg said I think we need to see more of your code to diagnose this problem.
I’m also not sure why you think the fact that this is valid C++ code is helpful when attempting to figure out why it doesn’t compile as C? C++ is (largely) a superset of C so there’s any number of reasons why valid C++ code might not be syntactically correct C code, not least that C++ treats structs as classes!
Linked
Hot Network Questions
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.1.14.43159
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
- Remove From My Forums
-
Question
-
The line of code which is causing this error is:-
CD3DVertexCache *m_pVertexCache;
CD3DVertexCache is a class. Usually this is a stupid error meaning I’ve not included the header file for the class. However on this occasion I have included the header file for the class. Further more when I run the mouse cursor over the class name the little message box appears class CD3DVertexCache. Which tells me the compiler knows of the class identifier. I’m not sure why I’m getting the error message, wondering if someone can advise what other situations would cause this error to appear?
Thanks,
Paul.
Answers
-
Usually means that there is an error or omission in the previous line(s).
Check for a missing semi-colon or other error(s) in the line(s) immediately
*before* the one indicated by the error message.
Check also for a missing semi-colon at the end of class and structure definitions.
— Wayne
Это ошибка синтаксиса. Связана она с отсутствием необходимых разделителей между элементами языка. Компилятор ожидает, что некоторые элементы языка появятся прежде или после других элементов. Если этого не происходит, то он выдаем ошибку. Будем пробовать ее получить. Пишем код:
#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++ (лишние знаки, забытые
- Remove From My Forums
-
Вопрос
-
Hey guys,
I am learning C language and I am having some problems with my codes. Can anyone help me out ? ?
#include <stdio.h>
int main (void)
{
int num1, num2, sum;
printf (» Please Enter the First Number :n»);
int scanf(«%1f», num1);
printf (» Please Enter the Second Number :n»);
int scanf(«%1f», num2);sum = num1 + num2;
return sum;
}Output message :
1>—— Build started: Project: Add, Configuration: Debug Win32 ——
1>Compiling…
1>add2nums.c
1>d:projectaddadd2nums.c(7) : error C2143: syntax error : missing ‘;’ before ‘type’
1>d:projectaddadd2nums.c(9) : error C2143: syntax error : missing ‘;’ before ‘type’
1>Build log was saved at «file://d:ProjectAddDebugBuildLog.htm»
1>Add — 2 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========-
Перемещено
14 августа 2008 г. 8:16
Off Topic for Visual C# general (Moved from Visual C# Language to Off-Topic Posts (Do Not Post Here))
-
Перемещено
Ответы
-
Abhinav,
This forum is for the C# language, not C, so I recommend you try to do a web search on some «C tutorials» or such to get some examples in C.
Having said that, the error you’re getting has to do with the «int» types prior to the scanf() call. You should remove that as it’s not correct.
Try the following:
#include <stdio.h> int main (void) { float num1, num2, sum; printf (» Please Enter the First Number :n»); scanf(«%f», &num1); printf (» Please Enter the Second Number :n»); scanf(«%f», &num2); sum = num1 + num2; printf(«%f», sum); return 0; }
Document my code? Why do you think it’s called «code»?
-
Помечено в качестве ответа
Michael Sun [MSFT]Microsoft employee
14 августа 2008 г. 8:15
-
Помечено в качестве ответа
-
Knock, knock: this is a C# forum. Just look a bit down in the forum’s site front page to find the C++ forums.
Hans Passant.
-
Помечено в качестве ответа
Michael Sun [MSFT]Microsoft employee
14 августа 2008 г. 8:15
-
Помечено в качестве ответа
-
As the first responder pointed out, the «int» should not be in front of scanf() function. The compiler thinks you want to create an int varialbe, but rather than giving it a name, your calling scanf(). That won’t work.
-
Помечено в качестве ответа
Michael Sun [MSFT]Microsoft employee
14 августа 2008 г. 8:15
-
Помечено в качестве ответа
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