Table of Contents
Common G++ Errors
Summary
This is a guide to help you CS35ers make sense of g++ and its often cryptic error messages.
If you discover an error not listed here feel free to edit this wiki,
or send your error along with source code and an explanation to me — grawson1@swarthmore.edu
Weird Errors
If you are getting strange compiler errors when your syntax looks fine, it might be a good idea to check that your Makefile is up to date
and that you are including the proper .h files. Sometimes a missing } or ; or ) will yield some scary errors as well.
Lastly, save all files that you might have changed before compiling.
Bad Code Sample
What’s wrong with the following code? (Hint: there are two errors)
#include<iostream> using namespace std; int main(){ int foo; for(int i = 0, i<100, i++) { foo++; cout << foo << endl; } return 0; }
When compiled this yields:
junk.cpp:9: error: expected initializer before '<' token
junk.cpp:13: error: expected primary-expression before 'return
‘
junk.cpp:13: error: expected `;' before 'return
‘
junk.cpp:13: error: expected primary-expression before 'return
‘
junk.cpp:13: error: expected `)' before 'return
‘
First, the parameters of the for
loop need to be separated by semicolons, not commas.
for(int i = 0; i<100; i++) { foo++; cout << foo << endl; }
Now look at this sample output of the corrected code:
-1208637327
-1208637326
-1208637325
-1208637324
-1208637323
-1208637322
Why the weird values? Because we never initialized foo
before incrementing it.
int foo = 0;
‘cout’ was not declared in this scope
Two things to check here:
(1) Did you add
#include<iostream>
to your list of headers?
(2) Did you add
using namespace std;
after your #includes?
‘printf’ was not declared in this scope
Add
#include<cstdio>
to your list of headers. Note if you are coming from C programming, adding
#include<cstdio> is preferred in C++ over #include <stdio.h>.
Cannot Pass Objects of non-POD Type
junk.cpp:8: warning: cannot pass objects of non-POD type 'struct std::string' through '…'; call will abort at runtime
junk.cpp:8: warning: format '%s' expects type 'char*', but argument 2 has type 'int
‘
What this usually means is that you forgot to append .c_str() to the name of your string variable when using printf.
This error occurred when trying to compile the following code:
int main(){ string foo = "dog"; printf("This animal is a %s.n",foo); return 0; }
Simply appending to .c_str() to “foo” will fix this:
printf("This animal is a %s.n",foo.c_str());
The reason you got this error is because printf is a C function and C handles strings differently than C++
Invalid Use of Member
junk.cpp:8: error: invalid use of member (did you forget the '&' ?)
What this usually means is that you forget to add () to the end of a function call.
Ironically, every time I see this it is never because I forgot the ‘&’.
This error occurred when trying to compile the following code:
int main(){ string foo = "dog"; printf("This animal is a %s.n",foo.c_str); return 0; }
Simply adding the open and close parentheses () will take care of this for you:
printf("This animal is a %s.n",foo.c_str());
Request for Member ‘Foo’ in ‘Bar’, which is of non-class type ‘X’
trycredit.cpp:86: error: request for member 'print' in 'card', which is of non-class type 'CreditCard*
‘
What this usually means is that you are using a ‘.’ between the class pointer and the function you are trying to call.
Here is an example from the CreditCard lab:
void useCard(CreditCard *card, int method) { //Used to access the methods of the class if (method==1) { card.print(); }
Since card
is a CreditCard* we need → rather than . Fixed:
if (method==1) { card->print(); }
Undefined Reference to V Table
This error usually means you need to add a destructor to your myClass.cpp/myClass.inl code.
If you don’t want to implement a real destructor at this point, you can write something like this:
myClass::~myClass(){}
So long as the destructor exists, you should now be able to compile fine. Of course,
implement a real destructor at a later point.
asiniy 0 / 0 / 0 Регистрация: 29.02.2012 Сообщений: 8 |
|||||||||||||||||||||
1 |
|||||||||||||||||||||
29.02.2012, 20:40. Показов 8299. Ответов 21 Метки нет (Все метки)
Здравствуйте! Я — абсолютный новичок в программировании на C. Нашёл учебник Кернигана и Ричи. В нём — helloworld.
Я компилирую файл: cc HELLO.C HELLO.C:1:7: error: ISO C++ forbids declaration of ‘MAIN’ with no type Далее я копирую содеримое файла hello.C, найденного в интернете:
Компиляция проходит успешно. Однако дальше проблема. Учебник говорит мне: Прогон его по команде A.OUT я в sh ввожу a.out, однако результатов никаких. Просьба, во-первых, объяснить, что значат эти строки:
А также посоветуйте учебник по программированию. Спасибо, Александр
__________________
0 |
Заблокирован |
|||||||||||||||||
29.02.2012, 21:03 |
2 |
||||||||||||||||
Советую самый лучший учебник по программированию от создателей языка С Керниган и Ричи Добавлено через 4 минуты
Это заголовочный файл. Все вызываемые функции как например printf(); где-то хранятся. Компилятор не знает где, поэтому ему надо об этом сказать. При запуске данной программы ты на очень короткое время увидишь черный экран консоли который сразу иcчезнет.
Добавлено через 7 минут <удалено>
1 |
0 / 0 / 0 Регистрация: 29.02.2012 Сообщений: 8 |
|
29.02.2012, 21:16 [ТС] |
3 |
Советую самый лучший учебник по программированию от создателей языка С Керниган и Ричи Я его и использую; но там нет про include stdio.h и return 0; (который, кстати, и не нужен). И, да, void не работает. Работает int. При запуске данной программы ты на очень короткое время увидишь черный экран консоли который сразу иcчезнет. Я его не вижу вообще. Добавление getchar(); проблемы не решает
0 |
Заблокирован |
||||
29.02.2012, 21:30 |
4 |
|||
Для начала всегда соблюдай синтаксис. В этом коде ошибок нет.
Если он у тебя не компилится, значит проблема в чем-то другом.
1 |
Ruzal |
|
29.02.2012, 22:00 |
5 |
Здравствуйте! |
Заблокирован |
|
29.02.2012, 22:05 |
6 |
Во время изучения языка — все равно. Сразу С а потом С++
0 |
0 / 0 / 0 Регистрация: 29.02.2012 Сообщений: 8 |
|
29.02.2012, 22:07 [ТС] |
7 |
А теперь подробно расскажи на чем компилишь и как создаешь проект Через утилиту cc — в sh ввожу cc hello.c
0 |
Заблокирован |
|
29.02.2012, 22:10 |
8 |
Я так понимаю все на Линуксе делаешь, тогда помочь не могу обращайся к линуксистам.
0 |
0 / 0 / 0 Регистрация: 29.02.2012 Сообщений: 8 |
|
29.02.2012, 22:13 [ТС] |
9 |
Намёк на переход с соседнюю тему?
0 |
go 3645 / 1377 / 243 Регистрация: 16.04.2009 Сообщений: 4,526 |
||||
29.02.2012, 22:15 |
10 |
|||
В этом коде ошибок нет. Громко сказано. Совет: пишите все в нижнем регистре, т.к. в Си (в отличии от Паскаля, например) это разные вещи получатся. Добавлено через 1 минуту
1 |
Заблокирован |
|
29.02.2012, 22:16 |
11 |
go, Ты имеешь ввиду «N», дык это его печеньки, пусть грызет.
0 |
asiniy 0 / 0 / 0 Регистрация: 29.02.2012 Сообщений: 8 |
||||
29.02.2012, 22:17 [ТС] |
12 |
|||
go, спасибо, работает. Можете привести какой-нибудь учебник по c, где есть все нововведения, типа
0 |
0 / 0 / 0 Регистрация: 29.02.2012 Сообщений: 8 |
|
29.02.2012, 22:25 [ТС] |
14 |
Благодарю Ну пока хватит, потом может ещё что прочту. Я рубист вообще
0 |
Nameless One 5826 / 3477 / 358 Регистрация: 08.02.2010 Сообщений: 7,448 |
||||||||
01.03.2012, 07:06 |
15 |
|||||||
В этой программе есть одна ошибка пропущено слово void нет. Функция main по стандарту должна возвращать int. Если спецификатор возвращаемого значения пропущен, то считается, что функция по умолчания возвращает int
я в sh ввожу a.out, однако результатов никаких В Linux (в отличиет от Windows) поиск исполняемых файлов происходит только в директориях, указанных в $PATH. В текущей директории исполняемые файлы не ищутся, поэтому нужно при запуске явно указать путь к исполняемому файлу, абсолютный:
или относительный (если файл находится в текущей директории)
А вообще я бы посоветовал для сборки использовать Make-файлы Добавлено через 3 минуты
Можете привести какой-нибудь учебник по c, где есть все нововведения, типа этим нововведениям уже не один десяток лет. Просто ты используешь древнюю версию книги. На русском есть второе издание, выпущенное в 2009 г., там таких косяков нет
1 |
Заблокирован |
|
01.03.2012, 17:53 |
16 |
st НЕ НЕТ, а да. int должен возвращаться в С++, а в С должен возвращаться void (т.е. ничего) А автор ветки пишет пока что на С, вот и пусть пишет как надо в С.
0 |
5826 / 3477 / 358 Регистрация: 08.02.2010 Сообщений: 7,448 |
|
01.03.2012, 17:57 |
17 |
int должен возвращаться в С++, а в С должен возвращаться void (т.е. ничего) ой-ой-ой, как интересно. Может, ткнешь меня носом в раздел стандарта, где это написано? Или мне самому из него цитату привести?
Unix и DOS не нуждаются чтобы им возвращали какие-то значения, это только винда выклянчивает у каждой программы нолик. Иначе она коректно работать не может. Бред. Феерический.
0 |
Заблокирован |
|||||
01.03.2012, 17:58 |
18 |
||||
nix и DOS не нуждаются чтобы им возвращали какие-то значения, это только винда выклянчивает у каждой программы нолик. Иначе она коректно работать не может. Хам и зазнайка
0 |
5826 / 3477 / 358 Регистрация: 08.02.2010 Сообщений: 7,448 |
|
01.03.2012, 18:00 |
19 |
IFree Host, аргументы есть? Или скажешь, что я был не прав?
0 |
Заблокирован |
|||||
01.03.2012, 18:02 |
20 |
||||
Не, если быть до конца честным, то со стандартами еще не удосужился ознакомиться. А вообще говорю то, что нам проф выдает. А он мудлан еще тот. На кучу вопросов нет ответов.
0 |
Comments
krrk
mentioned this issue
Feb 24, 2018
anton-malakhov
pushed a commit
to anton-malakhov/numba
that referenced
this issue
Sep 6, 2018
Fixed compilation on windows (with exception)
seibert
pushed a commit
that referenced
this issue
Sep 10, 2018
Add some torture tests to with objmode ctx.
PokhodenkoSA
added a commit
to PokhodenkoSA/numba
that referenced
this issue
Aug 9, 2020
kozlov-alexey
added a commit
to kozlov-alexey/numba
that referenced
this issue
Aug 17, 2020
PokhodenkoSA
added a commit
to PokhodenkoSA/numba
that referenced
this issue
Nov 12, 2020
Hardcode84
added a commit
to Hardcode84/numba
that referenced
this issue
Nov 17, 2020
Call lowering refactoring, numpy `add` and getitem
cluePrints
added a commit
to cluePrints/numba
that referenced
this issue
May 10, 2022
Bumped into this https://reviews.llvm.org/D67122 ``` OMP: Info numba#271: omp_set_nested routine deprecated, please use omp_set_max_active_levels instead. tmp/numba/0.53.1/numba/np/ufunc/omppool.cpp:185: runtime error: applying non-zero offset 96 to null pointer #0 0x7f86f24bc95a in .omp_outlined. tmp/numba/0.53.1/numba/np/ufunc/omppool.cpp:185 numba#1 0x7f8706cfaa22 in __kmp_invoke_microtask /tmp/openmp/12/src/openmp/runtime/src/z_Linux_asm.S:1166 numba#2 0x7f8706c8e5eb in __kmp_invoke_task_func /tmp/openmp/12/src/openmp/runtime/src/kmp_runtime.cpp:7308:30 numba#3 0x7f8706c8d288 in __kmp_launch_thread /tmp/openmp/12/src/openmp/runtime/src/kmp_runtime.cpp:5829:34 numba#4 0x7f8706ce115a in __kmp_launch_worker(void*) /tmp/openmp/12/src/openmp/runtime/src/z_Linux_util.cpp:591:33 numba#5 0x7f872e497c2e in start_thread /tmp/glibc/2.34/src/glibc-2.34/nptl/pthread_create.c:434:8 numba#6 0x7f872e52a1fb in clone3 /tmp/glibc/2.34/src/glibc-2.34/misc/../sysdeps/unix/sysv/linux/x86_64/clone3.S:81 SUMMARY: UndefinedBehaviorSanitizer: nullptr-with-nonzero-offset tmp/numba/0.53.1/numba/np/ufunc/omppool.cpp:185 in ```
- Forum
- The Ubuntu Forum Community
- Ubuntu Specialised Support
- Development & Programming
- Programming Talk
- error: ‘printf’ was not declared in this scope
-
error: ‘printf’ was not declared in this scope
Hi,
I want to try the code below and It is a code with preprocessors. I get an error.
Can anyone can tell me the reason?
Code:
#define HATALI(A) A*A*A /* Kup icin hatali makro */ #define KUP(A) (A)*(A)*(A) /* Dogusu ... */ #define KARE(A) (A)*(A) /* Karesi icin dogru makro */ #define START 1 #define STOP 9 main() { int i,offset; offset = 5; for (i = START;i <= STOP;i++) { printf("%3d in karesi %4d dir, ve kubu ise %6d dir..n", i+offset,KARE(i+offset),KUP(i+offset)); printf("%3d in HATALIsi ise %6d dir.n",i+offset,HATALI(i+offset)); } }
the error:
Code:
'printf' was not declared in this scope
-
Re: error: ‘printf’ was not declared in this scope
-
Re: error: ‘printf’ was not declared in this scope
WW ,
Thanks for helpwhen included the <studi> header file
it returned an error:
Code:
studio.h: No such file or directory
I am using gcc compiler. Can this be the reason?
-
Re: error: ‘printf’ was not declared in this scope
-
Re: error: ‘printf’ was not declared in this scope
WW,thanks.
I’m so inattentiveanyway, the program give a more garbled error…
what does this error mean?
how can I fix the problem?
Code:
/tmp/ccGQNcoh.o:(.eh_frame+0x11): undefined reference to `__gxx_personality_v0' collect2: ld output returned 1
-
Re: error: ‘printf’ was not declared in this scope
What command did you use that results in that error?
-
Re: error: ‘printf’ was not declared in this scope
I’m using vi editor and first of all I created a file like this:
Code:
user@user-desktop:~$ vi example_macro.cpp
then I compiled the file by the command:
Code:
sh-3.1$ gcc example_macro.cpp -o objmacro
by the way I have a off topic question,
I have created a file:user@user-desktop:~$ mkdir make_file_work
then I go and look both the ‘user’ file and to the ‘desktop’ I cannot find such a directory? But if I write the command:
user@user-desktop:~$ cd make_file_work
I can go inside that file, but I cannot see it in the file browser…
why?
thanks again for your help WW…
-
Re: error: ‘printf’ was not declared in this scope
You appear to be writing C, not C++. Rename the file to example_macro.c, and try again. (I just tried it both ways; I got the same error that you did when the file was called example_macro.cpp, and it compiled fine when I called it example_macro.c.)
-
Re: error: ‘printf’ was not declared in this scope
It’ll compile as a .cpp if you put the line…
Code:
using namespace std;
under the include for stdio.h, or preface printf with «std::» in order to tell the compiler that you’re using a function from the standard namespace.
-
Re: error: ‘printf’ was not declared in this scope
Yes, it compiled when I changed the extesion from .cpp to .c. But I dont know the diferrences between the c and cpp.
Does the reason depends to ‘printf’ function? Because, as far as I remember I use cout function instead of printf in cpp. I guess printf is a c function…
But when I tried with
#include <stdio>
using namespace std;it gave an error again. the error the same:
Code:
/tmp/ccubDW3d.o:(.eh_frame+0x11): undefined reference to `__gxx_personality_v0' collect2: ld output return 1
what does this error mean anyway?
«/tmp/ccubDW3d.o» :……………………………………what is the object ccubDW3d.o in the ‘tmp’ directory?
«(.eh_frame+0x11)» :………………………………….. can this be an address?
«undefined reference to `__gxx_personality_v0′» : it says ‘__gxx_personality_v0’ and says there is an undefined reference to this ‘thing’. But I’ve not use that thing in my . ………………………………………….. …………………..code. What does it refer to in my code?
«collect2: ld output return 1» : what is collect 2? What is ld output? What does returning 1 means?WW and Mime thanks for help
Last edited by ankakusu; June 3rd, 2007 at 11:10 AM.