Recommended Answers
Make sure there is a carriage return at the end of the last line.
Some compilers are picky.
Jump to Post
Hi,I spent all night trying to figure this out. Could someone take a look and show me what I’m missing? I getting this compiler error: unterminated #ifndef . But I have ifndef at the beginning and endif at the end of the class.
//Header file. //Class definition for …
Jump to Post
All 5 Replies
thines01
401
Postaholic
Team Colleague
Featured Poster
Make sure there is a carriage return at the end of the last line.
Some compilers are picky.
Hi,I spent all night trying to figure this out. Could someone take a look and show me what I’m missing? I getting this compiler error: unterminated #ifndef . But I have ifndef at the beginning and endif at the end of the class.
//Header file. //Class definition for teh stack ADT #ifndef _mystack_H #include <ostream> #include <fstream> #include <stdio.h> #include <stdlib.h> #include <time.h> #define _mystack_H const unsigned int maxSize = 10; class Stack { public: Stack(); //constructor ~Stack(); //Destructor bool isEmptyStack(); bool isFullStack(); void pushStack(int newItem); void popStack(int item); void initializeStack(); void fillStack(int numSize); void exchangeTopAndBottom(Stack &stk); void printStack(Stack &stk); int sumStack(Stack &stk); void OddElem(Stack &stk); //void commonStack(Stack &stk1, Stack &stk2); void intersectStack(Stack &stk1, Stack &stk2); private: int maxSize; //variable to store the maximum stack size int stackTop; //variable to poit to the top of the stack Stack arrList;//pointer to the array that holds the stack //elements }; #endif
First of all, «Stack arrList» —this is not legal as far as I know in C++. This should be Stack* arrlist. Fix this first and try it.
I’m not sure about your #ifndef problem. I copy/pasted your code and it compiled after I fixed the Stack*. My guess is that it’s one of your overlapping includes that’s not being properly handled by your particular compiler.
fstream automatically includes ostream. Here’s a map of how that works:
http://www.cplusplus.com/reference/iostream/
Anything that an arrow points to, will automatically include its parent class, tracing backwards. So you only need to include fstream. First remove #include <ostream> and try to compile. Pretty sure stdio automatically includes stdlib, too. You should try to remove one or the other. Stdio is C input output. In my opinion you shouldn’t use both the C++ streams library and the Stdio library, as they both perform similar tasks.
You should #include as few things as possible. Not only does it bloat your code, but it can confuse your compiler as well.
Edited
by Greywolf333 because:
n/a
LevyDee
2
Posting Whiz in Training
You need to format your defines as such:
#ifndef
#define
#endif
after you said #ifndef _mystack_H
you need to then put a #define right after that on line 5
murnesty
0
Junior Poster in Training
It may caused by previous header file
BoBok2002
0
Junior Poster in Training
It worked! I repositioned the ifndef, define, and endif. Then I changed #include <ostream> to #include <iostream> and I compiled the code on a different compiler, and it worked. I fixed the Stack *arrList too.
Now I’m getting another error. The last one I hope. It says
[Linker error] undefined reference to `Stack::Stack()’
And there is a linker error displayed for all the functions in my implementation file. Also, #include «mystack.h» has been highlighted in both the main and implementation file. Please help me with this one too.
Thanks.
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
- Forum
- Beginners
- error : unterminated #ifndef
error : unterminated #ifndef
Hey, umm I’m a beginner at c++ and have no idea why this error is happening
error : unterminated #ifndef
Burrito2.h
|
|
main.cpp
|
|
Burrito2.cpp
|
|
Last edited on
Does the compiler state the file, where error occurs?
Hello sohui,
In addition to keskiverto‘s question are the line numbers in the files?
When I loaded up your files in my IDE, (VS2017), minus the line numbers I could not duplicate your error.
Not sure what you did using the code tags, but they do not put the line numbers in side the block unless you copy a pasted it that way.
In «Burrito2.cpp» you have:
|
|
Sometimes this will make no difference, but at other times it does. I tend to like this order better.
|
|
I like the «.hpp»extension better than the «.h» extension when using a C++ program. The «.h» makes me think it is a C header file when it is not.
With «Burrito2.hpp» being last the header file(s) that come before are compiled first and anything in the «Burrito2.hpp» file that would need the above header files is covered. I use the blank line to break the standard include files the ones in the (<>)s from the files that I would write, the ones in («»)s.
Hope that helps,
Andy
I was able to run code without errors and didn’t edit the files. Maybe try BURRITO2_H_
.
Topic archived. No new replies allowed.
Есть два класса, которые связаны друг с другом в своих заголовках:
PlotMarker
#ifndef PLOTMARKER_H
#define PLOTMARKER_H
#include <QObject>
#include "plotter.h"
class Plotter;
class PlotMarker : public QObject
{
// ...
Plotter* m_attachedPlot;
// ...
};
#endif // PLOTMARKER_H
графопостроитель
#ifndef PLOTTER_H
#define PLOTTER_H
// ...
#include "plotmarker.h"// ...
class PlotMarker;
class Plotter : public QQuickPaintedItem
{
// ...
QLinkedList<PlotMarker*> m_markerList;
// ...
};
#endif // PLOTTER_H
Программа скомпилирована хорошо, но есть ошибка error: unterminated conditional directive
в #ifndef
и код классов в IDE не выделяется из-за этого.
Если я удалю #include "plotter.h"
в заголовке PlotMarker или #include "plotmarker.h"
в заголовке Plotter Qt Creator подсвечивает код как обычно, но компиляция завершается неудачно из-за ошибок о недопустимом использовании неполного типа.
Не могли бы вы сказать мне, что не так? Я думаю, что это из-за неправильных перекрестных ссылок заголовков, но я столкнулся с этот и это не помогло мне.
1
Решение
Проблема решена.
Я только что переехал один из #include
из заголовка в исходный файл, и это сработало.
plotmarker.h
#ifndef PLOTMARKER_H
#define PLOTMARKER_H
#include <QObject>
class Plotter;
class PlotMarker : public QObject
{
// ...
Plotter* m_attachedPlot;
// ...
};
#endif // PLOTMARKER_H
// …
plotmarker.cpp
#include "plotmarker.h"#include "plotter.h"// ...
2
Другие решения
Других решений пока нет …
Gus 26 / 37 / 10 Регистрация: 17.02.2009 Сообщений: 364 |
||||||||
1 |
||||||||
07.03.2012, 16:34. Показов 3822. Ответов 31 Метки нет (Все метки)
После переустановки Devcpp и переписания сервера с нуля, посыпались ошибки LinkerError
Их много, копировать все не буду.
зы, не доделан, не дает откомпилится проекту, и просмотреть ошибки. Добавлено через 4 часа 20 минут
0 |
dr.curse 403 / 359 / 36 Регистрация: 11.10.2010 Сообщений: 1,907 |
||||
07.03.2012, 16:38 |
2 |
|||
так попробуй
1 |
62 / 62 / 11 Регистрация: 16.10.2011 Сообщений: 200 |
|
07.03.2012, 17:21 |
3 |
Нигде не вижу строчки с подключением библиотеки.
0 |
26 / 37 / 10 Регистрация: 17.02.2009 Сообщений: 364 |
|
07.03.2012, 17:25 [ТС] |
4 |
Нигде не вижу строчки с подключением библиотеки. Я его добавил в параметрах проекта
0 |
26 / 37 / 10 Регистрация: 17.02.2009 Сообщений: 364 |
|
07.03.2012, 17:29 [ТС] |
5 |
aram_gyumri, большинство ошибок исчезло, спасибо, но вот некоторые остались Миниатюры
0 |
Жарю без масла 867 / 749 / 225 Регистрация: 13.01.2012 Сообщений: 1,702 |
|
07.03.2012, 17:58 |
6 |
скорее всего ваш header включается в несколько единиц трансляции. поэтому были «multiple definition of…». определения ф-ий поместите в отдельный сорс-файл и добавьте там же определения статических переменных класса.
0 |
5039 / 2618 / 241 Регистрация: 07.10.2009 Сообщений: 4,310 Записей в блоге: 1 |
|
07.03.2012, 18:18 |
7 |
#pragma_once вроде мелкомягкая фишка, а если используется MinGW — значит толку от нее ноль. Вставляйте include guard’ы.
0 |
Жарю без масла 867 / 749 / 225 Регистрация: 13.01.2012 Сообщений: 1,702 |
|
07.03.2012, 18:25 |
8 |
дело не только в гардах. они нужны, но может возникнуть и следущий сценарий:
0 |
26 / 37 / 10 Регистрация: 17.02.2009 Сообщений: 364 |
|
07.03.2012, 18:31 [ТС] |
9 |
Эти ошибки лезут везде, где используются статичные функции. Гуглил по этому поводу ничего дельного не нашел
0 |
Жарю без масла 867 / 749 / 225 Регистрация: 13.01.2012 Сообщений: 1,702 |
|
07.03.2012, 18:39 |
10 |
сделайте как сказано выше: объявления в заголовках, определения в исходниках
0 |
Gus 26 / 37 / 10 Регистрация: 17.02.2009 Сообщений: 364 |
||||
07.03.2012, 18:54 [ТС] |
11 |
|||
В результате ничего не поменялось (если я верно понял)
0 |
retmas Жарю без масла 867 / 749 / 225 Регистрация: 13.01.2012 Сообщений: 1,702 |
||||
07.03.2012, 19:02 |
12 |
|||
писал же… где определения статических переменных класса? Добавлено через 1 минуту
0 |
Gus 26 / 37 / 10 Регистрация: 17.02.2009 Сообщений: 364 |
||||
07.03.2012, 19:07 [ТС] |
13 |
|||
0 |
retmas Жарю без масла 867 / 749 / 225 Регистрация: 13.01.2012 Сообщений: 1,702 |
||||
07.03.2012, 19:20 |
14 |
|||
вы знаете разницу между переменными и ф-ми?
unterminated #ifndef ну прочитайте хоть… не понимаете английский — есть переводчик. для вашего #ifndef нет завершения (#endif) Добавлено через 56 секунд
static DWORD ChebTCPServerSocket::ClientThread(void*) уберите static из определения. оно нужно только в объявлении в заголовке Добавлено через 2 минуты
DWORD WINAPI ChebTCPServerSocket::ClientAccept(LPVOID Nothing); не нужны — они есть в заголовке(в объявлении класса). в исходнике — определения
1 |
Gus 26 / 37 / 10 Регистрация: 17.02.2009 Сообщений: 364 |
||||
07.03.2012, 19:23 [ТС] |
15 |
|||
вы знаете разницу между переменными и ф-ми? ну прочитайте хоть… не понимаете английский — есть переводчик. для вашего #ifndef нет завершения (#endif) да, проглядел. Я почитал в вики про гуарды, вот ifndef пропустил, но вот как поставил его на место, ошибки
Копировал на выбор.
0 |
Жарю без масла 867 / 749 / 225 Регистрация: 13.01.2012 Сообщений: 1,702 |
|
07.03.2012, 19:26 |
16 |
читайте сообщения выше. я уже объяснил все в предыдущих постах. если не понятно — изучайте, чем отличается объявление от определения (хотя я уж и на примере показал)
0 |
Gus 26 / 37 / 10 Регистрация: 17.02.2009 Сообщений: 364 |
||||||||
07.03.2012, 19:42 [ТС] |
17 |
|||||||
ChebTCP.h
ChebTCP.cpp
0 |
Жарю без масла 867 / 749 / 225 Регистрация: 13.01.2012 Сообщений: 1,702 |
|
07.03.2012, 19:53 |
18 |
ClientAccept и ClientThread должны возвращать значения. в остальном должно скомпилиться
0 |
26 / 37 / 10 Регистрация: 17.02.2009 Сообщений: 364 |
|
07.03.2012, 19:57 [ТС] |
19 |
Дело в том что не компилится) должно да не обязано как говорится)
0 |
Жарю без масла 867 / 749 / 225 Регистрация: 13.01.2012 Сообщений: 1,702 |
|
07.03.2012, 19:59 |
20 |
дубль два
ClientAccept и ClientThread должны возвращать значения. Добавлено через 53 секунды
0 |
i am currently having problem rectifying this error in my dev c++ project, here is my code:
#ifndef GRAPHICS_H
#define GRAPHICS_H
struct SDL_Window;
struct SDL_Renderer;
class Graphics {
public:
Graphics();
~Graphics();
private:
SDL_Window* _window;
SDL_Renderer* _renderer;
};
But the compiler says «unterminated #ifndef» and expected initializer before ‘~’ token, i have tried to fix this problem for more than 3 hours but still couldn’t fix this.
- c++
- sdl
asked Oct 13, 2015 at 16:01
user2891869user2891869
5691 gold badge4 silver badges12 bronze badges
3
-
You forgot to add
#endif
at the endOct 13, 2015 at 16:01
-
If you just enter that error in Google you get an explanation in one of the first results. If you really spent 3 hours on this, don’t focus on working more, focus on working more effectively.
– user743382
Oct 13, 2015 at 16:07
-
You should add
#endif
in the file. However, that does not explain the other error. It will be good if you can post an MCVE.Oct 13, 2015 at 16:07
1 Answer
#ifndef GRAPHICS_H
#define GRAPHICS_H
#ifndef
statements need to be closed by an #endif
. You should probably add it to the end of your file so you keep everything in it within the scope of GRAPHICS_H.
answered Oct 13, 2015 at 16:04
Floris VellemanFloris Velleman
4,8484 gold badges29 silver badges46 bronze badges
4
-
thanks, that really worked but in my «graphics.cpp» file, in the code Graphics::Graphics()~Graphics() { SDL_DestroyWindow(this->_window); } , it showed expected initializer before ‘~’ token can you help me with this?
Oct 13, 2015 at 16:07
-
@user2891869 if you have another question you should ask another question.
Oct 13, 2015 at 16:08
-
try
Graphics::~Graphics() { SDL_DestroyWindow(this->_window); }
.Oct 13, 2015 at 16:09
-
@user2891869 If this answered your question then please mark the answer as such.
Oct 14, 2015 at 7:07