Unterminated ifndef ошибка


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

Member Avatar for thines01


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.

Member Avatar for Greywolf333


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

Member Avatar for LevyDee


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

Member Avatar for murnesty


murnesty

0



Junior Poster in Training



It may caused by previous header file

Member Avatar for BoBok2002


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

1
2
3
4
5
6
7
8
9
10
11
12
1 #ifndef BURRITO2_H
2 #define BURRITO2_H
3 
4 
5 class Burrito2
6 {
7     public:
8         Burrito2();
9         
10 };
11 
12 #endif // BURRITO2_H 

main.cpp

1
2
3
4
5
6
7
8
9
1 #include <iostream>
2 #include "Burrito2.h"
3 using namespace std;
4
5 int main()
6 {
7     Burrito2 bo;
8     return 0;
9 }

Burrito2.cpp

1
2
3
4
5
6
7
8
9
1 #include "Burrito2.h"
2 #include <iostream>
3
4 using namespace std;
5
6 Burrito2::Burrito2()
7 {
8     cout << "i am a banana" << endl;
9 }

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:

1
2
#include "Burrito2.hpp"
#include <iostream> 

Sometimes this will make no difference, but at other times it does. I tend to like this order better.

1
2
3
#include <iostream>

#include "Burrito2.hpp" 

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

C++
1
2
3
4
5
  [Linker error] undefined reference to `ChebTCPServerSocket::ServerSocket' 
 C:\Users\Ìèõàèë\Desktop\SCheb21\main.o(.text+0x156) In function `ZN19ChebTCPServerSocket12ClientAcceptEPv': 
 C:\Users\Ìèõàèë\Desktop\SCheb21\cheb21.o(.text+0x0) In function `ZN19ChebTCPServerSocket11StartServerEv': 
51 C:\Users\Ìèõàèë\Desktop\SCheb21\ChebTCP.h multiple definition of `ChebTCPServerSocket::StartServer()' 
95 C:\Users\Ìèõàèë\Desktop\SCheb21\ChebTCP.h multiple definition of `_ZN19ChebTCPServerSocket12ClientThreadEPv@4'

Их много, копировать все не буду.
Вот сам код header’a

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <windows.h>
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <winsock2.h>
//#include "cheb21.h"
#pragma once
#define BUFFSIZE 4096
#define MAXCONNECTION 500
using namespace std;
//------------------------------------------------------------------------------
struct UserOnline{
    bool registred;
    char IP[16];
    int ID;
    int IDOnline;
    SOCKET UserSocket;
    int SendText(char buff[BUFFSIZE]);
};
//------------------------------------------------------------------------------
class ChebTCPServerSocket{
public:
    short int PORT;
    int MAXCONNECTIONS;
    static int COUNT;
    //Functions
    int StartServer();
    int StopServer();
    static UserOnline *User;
private:
    static  bool ServerActive;
    static SOCKET ServerSocket;
    static SOCKET TempSocket;
    static DWORD WINAPI ClientAccept(LPVOID Nothing);
    static DWORD WINAPI ClientThread(LPVOID User);
};
//------------------------------------------------------------------------------
int ChebTCPServerSocket::StartServer()
{
    if(PORT==0){return -1;}
    WSADATA *WsaData;
    if(WSAStartup(0x202,WsaData))
    ServerSocket=socket(AF_INET,SOCK_STREAM,0);
    if(ServerSocket==INVALID_SOCKET){return -2;}
    sockaddr_in ServerAddr;
    ServerAddr.sin_family=AF_INET;
    ServerAddr.sin_port=htons(PORT);
    ServerAddr.sin_addr.s_addr=0;
    if(bind(ServerSocket,(sockaddr *)&ServerAddr,sizeof(ServerAddr))!=0)
    {return -3;}
    if(listen(ServerSocket,0x100))
    {return -4;}
    ServerActive=true;
    CreateThread(0,0,&ClientAccept,0,0,0);
    return 0;
}
//------------------------------------------------------------------------------
DWORD WINAPI ChebTCPServerSocket::ClientAccept(LPVOID Nothing)
{
    sockaddr ClientAddr;
    int ClientAddrSize=sizeof(ClientAddr);
    int Id;
    while((TempSocket=accept(ServerSocket,&ClientAddr,&ClientAddrSize))&&ServerActive==true)
    {
        COUNT++;
        User=new UserOnline;
        HOSTENT *hst;
        hst=gethostbyname((char*)&ClientAddr);
 
        for(Id=0;Id<sizeof(User);Id++)
        {
            if(User[Id].ID==0&&User[Id].IDOnline==0&&User[Id].IP=="")
            {
                strcat(User[Id].IP,(char*)&ClientAddr);
                User[Id].IDOnline=Id;
                break;
            }
        }
    CreateThread(0,0,&ClientThread,&User[Id],0,0);
    }
}
//------------------------------------------------------------------------------
    DWORD WINAPI ChebTCPServerSocket::ClientThread(LPVOID User)
    {
        UserOnline *Usermem;
        Usermem=(UserOnline *)User;
        char buff[BUFFSIZE];
        while(int SizeRecv=recv(Usermem->UserSocket,buff,BUFFSIZE,0)&&SizeRecv==INVALID_SOCKET)
        {}
        delete Usermem;
    }
//------------------------------------------------------------------------------

зы, не доделан, не дает откомпилится проекту, и просмотреть ошибки.

Добавлено через 4 часа 20 минут
Up! если что то не понятно в вопросе, отпишите.



0



dr.curse

403 / 359 / 36

Регистрация: 11.10.2010

Сообщений: 1,907

07.03.2012, 16:38

2

так попробуй

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#ifndef _CHEB_H_
#define _CHEB_H_
#include <windows.h>
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <winsock2.h>
//#include "cheb21.h"
#pragma once
#define BUFFSIZE 4096
#define MAXCONNECTION 500
using namespace std;
//------------------------------------------------------------------------------
struct UserOnline{
        bool registred;
        char IP[16];
        int ID;
        int IDOnline;
        SOCKET UserSocket;
        int SendText(char buff[BUFFSIZE]);
};
//------------------------------------------------------------------------------
class ChebTCPServerSocket{
public:
        short int PORT;
        int MAXCONNECTIONS;
        static int COUNT;
        //Functions
        int StartServer();
        int StopServer();
        static UserOnline *User;
private:
    static      bool ServerActive;
        static SOCKET ServerSocket;
        static SOCKET TempSocket;
        static DWORD WINAPI ClientAccept(LPVOID Nothing);
        static DWORD WINAPI ClientThread(LPVOID User);
};
//------------------------------------------------------------------------------
int ChebTCPServerSocket::StartServer()
{
        if(PORT==0){return -1;}
        WSADATA *WsaData;
        if(WSAStartup(0x202,WsaData))
        ServerSocket=socket(AF_INET,SOCK_STREAM,0);
        if(ServerSocket==INVALID_SOCKET){return -2;}
    sockaddr_in ServerAddr;
        ServerAddr.sin_family=AF_INET;
        ServerAddr.sin_port=htons(PORT);
        ServerAddr.sin_addr.s_addr=0;
        if(bind(ServerSocket,(sockaddr *)&ServerAddr,sizeof(ServerAddr))!=0)
        {return -3;}
        if(listen(ServerSocket,0x100))
        {return -4;}
        ServerActive=true;
        CreateThread(0,0,&ClientAccept,0,0,0);
        return 0;
}
//------------------------------------------------------------------------------
DWORD WINAPI ChebTCPServerSocket::ClientAccept(LPVOID Nothing)
{
        sockaddr ClientAddr;
        int ClientAddrSize=sizeof(ClientAddr);
        int Id;
        while((TempSocket=accept(ServerSocket,&ClientAddr,&ClientAddrSize))&&ServerActive==true)
        {
                COUNT++;
                User=new UserOnline;
                HOSTENT *hst;
        hst=gethostbyname((char*)&ClientAddr);
 
                for(Id=0;Id<sizeof(User);Id++)
                {
                        if(User[Id].ID==0&&User[Id].IDOnline==0&&User[Id].IP=="")
                        {
                                strcat(User[Id].IP,(char*)&ClientAddr);
                                User[Id].IDOnline=Id;
                            break;
                        }
                }
        CreateThread(0,0,&ClientThread,&User[Id],0,0);
        }
}
//------------------------------------------------------------------------------
        DWORD WINAPI ChebTCPServerSocket::ClientThread(LPVOID User)
        {
                UserOnline *Usermem;
                Usermem=(UserOnline *)User;
                char buff[BUFFSIZE];
                while(int SizeRecv=recv(Usermem->UserSocket,buff,BUFFSIZE,0)&&SizeRecv==INVALID_SOCKET)
                {}
                delete Usermem;
        }
//------------------------------------------------------------------------------
#endif



1



62 / 62 / 11

Регистрация: 16.10.2011

Сообщений: 200

07.03.2012, 17:21

3

Нигде не вижу строчки с подключением библиотеки.
Либо нужно прописать в начале мейна LoadLibrary(«Ws2_32.dll»)
Либо что-то вроде:
#pragma comment(lib, «Ws2_32.lib»)
Правда на счет второго варианта я не совсем уверен.



0



26 / 37 / 10

Регистрация: 17.02.2009

Сообщений: 364

07.03.2012, 17:25

 [ТС]

4

Цитата
Сообщение от darkknight2008
Посмотреть сообщение

Нигде не вижу строчки с подключением библиотеки.
Либо нужно прописать в начале мейна LoadLibrary(«Ws2_32.dll»)
Либо что-то вроде:
#pragma comment(lib, «Ws2_32.lib»)
Правда на счет второго варианта я не совсем уверен.

Я его добавил в параметрах проекта
../../../../Dev-Cpp/lib/libwsock32.a



0



26 / 37 / 10

Регистрация: 17.02.2009

Сообщений: 364

07.03.2012, 17:29

 [ТС]

5

aram_gyumri, большинство ошибок исчезло, спасибо, но вот некоторые остались

Миниатюры

Linker error
 



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

дело не только в гардах. они нужны, но может возникнуть и следущий сценарий:
пусть есть 2 файла file1.cpp file2.cpp. если они оба инклудят заголовок из 1го поста ТСа, можем получить определения одних и тех же методов в 2х сорсах независимо от наличия гардов => multiple definition.



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

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//ChebTCP.h
#ifndef _CHEB_H_
#define _CHEB_H_
#include <windows.h>
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <winsock2.h>
//#include "cheb21.h"
#pragma once
#define BUFFSIZE 4096
#define MAXCONNECTION 500
using namespace std;
//------------------------------------------------------------------------------
struct UserOnline{
    bool registred;
    char EMAIL[25];
    char IP[16];
    int ID;
    int IDOnline;
    SOCKET UserSocket;
    int SendText(char buff[BUFFSIZE]);
};
//------------------------------------------------------------------------------
class ChebTCPServerSocket{
public:
    short int PORT;
    int MAXCONNECTIONS;
    static int COUNT;
    //Functions
    int StartServer();
    int StopServer();
    static UserOnline *User;
private:
    static  bool ServerActive;
    static SOCKET ServerSocket;
    static SOCKET TempSocket;
    static DWORD WINAPI ClientAccept(LPVOID Nothing);
    static DWORD WINAPI ClientThread(LPVOID User);
};
//ChebTCP.cpp
#include <winsock2.h>
#include <iostream>
#include "ChebTCP.h"
using namespace std;
int ChebTCPServerSocket::StartServer()
{
    if(PORT==0){return -1;}
    WSADATA *WsaData;
    if(WSAStartup(0x202,WsaData))
    ServerSocket=socket(AF_INET,SOCK_STREAM,0);
    if(ServerSocket==INVALID_SOCKET){return -2;}
    sockaddr_in ServerAddr;
    ServerAddr.sin_family=AF_INET;
    ServerAddr.sin_port=htons(PORT);
    ServerAddr.sin_addr.s_addr=0;
    if(bind(ServerSocket,(sockaddr *)&ServerAddr,sizeof(ServerAddr))!=0)
    {return -3;}
    if(listen(ServerSocket,0x100))
    {return -4;}
    ServerActive=true;
    CreateThread(0,0,&ClientAccept,0,0,0);
    return 0;
}
//------------------------------------------------------------------------------
DWORD WINAPI ChebTCPServerSocket::ClientAccept(LPVOID Nothing)
{
    sockaddr ClientAddr;
    int ClientAddrSize=sizeof(ClientAddr);
    int Id;
    while((TempSocket=accept(ServerSocket,&ClientAddr,&ClientAddrSize))&&ServerActive==true)
    {
        COUNT++;
        User=new UserOnline;
        HOSTENT *hst;
        hst=gethostbyname((char*)&ClientAddr);
 
        for(Id=0;Id<sizeof(User);Id++)
        {
            if(User[Id].ID==0&&User[Id].IDOnline==0&&User[Id].IP=="")
            {
                strcat(User[Id].IP,(char*)&ClientAddr);
                User[Id].IDOnline=Id;
                break;
            }
        }
    CreateThread(0,0,&ClientThread,&User[Id],0,0);
    }
}
//------------------------------------------------------------------------------
    DWORD WINAPI ChebTCPServerSocket::ClientThread(LPVOID User)
    {
        UserOnline *Usermem;
        Usermem=(UserOnline *)User;
        char buff[BUFFSIZE];
        while(int SizeRecv=recv(Usermem->UserSocket,buff,BUFFSIZE,0)&&SizeRecv==INVALID_SOCKET)
        {}
        delete Usermem;
    }
//------------------------------------------------------------------------------

В результате ничего не поменялось (если я верно понял)



0



retmas

Жарю без масла

867 / 749 / 225

Регистрация: 13.01.2012

Сообщений: 1,702

07.03.2012, 19:02

12

писал же… где определения статических переменных класса?

Добавлено через 1 минуту

C++
1
2
3
4
//ChebTCP.cpp
int ChebTCPServerSocket::COUNT;
// ...
// и т.д.



0



Gus

26 / 37 / 10

Регистрация: 17.02.2009

Сообщений: 364

07.03.2012, 19:07

 [ТС]

13

C++
1
2
3
4
5
6
7
8
9
10
12:1 C:\Users\Ìèõàèë\Desktop\SCheb21\ChebTCP.h unterminated #ifndef 
11 C:\Users\Ìèõàèë\Desktop\SCheb21\ChebTCP.cpp declaration of `static DWORD ChebTCPServerSocket::ClientThread(void*)' outside of class is not definition 
//Внесенные изменения ChebTCP.cpp
int ChebTCPServerSocket::COUNT;
UserOnline *ChebTCPServerSocket::User;
bool ChebTCPServerSocket::ServerActive;
SOCKET ChebTCPServerSocket::ServerSocket;
SOCKET ChebTCPServerSocket::TempSocket;
DWORD WINAPI ChebTCPServerSocket::ClientAccept(LPVOID Nothing);
DWORD WINAPI ChebTCPServerSocket::ClientThread(LPVOID User);



0



retmas

Жарю без масла

867 / 749 / 225

Регистрация: 13.01.2012

Сообщений: 1,702

07.03.2012, 19:20

14

вы знаете разницу между переменными и ф-ми?

Цитата
Сообщение от Gus
Посмотреть сообщение

unterminated #ifndef

ну прочитайте хоть… не понимаете английский — есть переводчик. для вашего #ifndef нет завершения (#endif)

Добавлено через 56 секунд

Цитата
Сообщение от Gus
Посмотреть сообщение

static DWORD ChebTCPServerSocket::ClientThread(void*)

уберите static из определения. оно нужно только в объявлении в заголовке

Добавлено через 2 минуты
объявления

Цитата
Сообщение от Gus
Посмотреть сообщение

DWORD WINAPI ChebTCPServerSocket::ClientAccept(LPVOID Nothing);
DWORD WINAPI ChebTCPServerSocket::ClientThread(LPVOID User);

не нужны — они есть в заголовке(в объявлении класса). в исходнике — определения

C++
1
2
3
4
5
6
7
8
DWORD WINAPI ChebTCPServerSocket::ClientAccept(LPVOID Nothing)
{
...
}
DWORD WINAPI ChebTCPServerSocket::ClientThread(LPVOID User)
{
...
}



1



Gus

26 / 37 / 10

Регистрация: 17.02.2009

Сообщений: 364

07.03.2012, 19:23

 [ТС]

15

Цитата
Сообщение от retmas
Посмотреть сообщение

вы знаете разницу между переменными и ф-ми?

ну прочитайте хоть… не понимаете английский — есть переводчик. для вашего #ifndef нет завершения (#endif)

да, проглядел. Я почитал в вики про гуарды, вот ifndef пропустил, но вот как поставил его на место, ошибки

C++
1
2
95 C:\Users\Ìèõàèë\Desktop\SCheb21\ChebTCP.h multiple definition of `_ZN19ChebTCPServerSocket12ClientThreadEPv@4' 
 C:\Users\Ìèõàèë\Desktop\SCheb21\ChebTCP.o(.text+0x0) In function `ZN19ChebTCPServerSocket11StartServerEv':

Копировал на выбор.



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

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#ifndef _CHEBTCP_H_
#define _CHEBTCP_H_
#pragma once
#include <windows.h>
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <winsock2.h>
//#include "cheb21.h"
 
#define BUFFSIZE 4096
#define MAXCONNECTION 500
using namespace std;
//------------------------------------------------------------------------------
struct UserOnline{
    bool registred;
    char EMAIL[25];
    char IP[16];
    int ID;
    int IDOnline;
    SOCKET UserSocket;
    int SendText(char buff[BUFFSIZE]);
};
//------------------------------------------------------------------------------
class ChebTCPServerSocket{
public:
    short int PORT;
    int MAXCONNECTIONS;
    static int COUNT;
    //Functions
    int StartServer();
    int StopServer();
    static UserOnline *User;
private:
    static  bool ServerActive;
    static SOCKET ServerSocket;
    static SOCKET TempSocket;
    static DWORD WINAPI ClientAccept(LPVOID Nothing);
    static DWORD WINAPI ClientThread(LPVOID User);
};
//------------------------------------------------------------------------------
 #endif

ChebTCP.cpp

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <winsock2.h>
#include <iostream>
#include "ChebTCP.h"
using namespace std;
int ChebTCPServerSocket::COUNT;
UserOnline *ChebTCPServerSocket::User;
bool ChebTCPServerSocket::ServerActive;
SOCKET ChebTCPServerSocket::ServerSocket;
SOCKET ChebTCPServerSocket::TempSocket;
//DWORD WINAPI ChebTCPServerSocket::ClientAccept(LPVOID Nothing);
//DWORD WINAPI ChebTCPServerSocket::ClientThread(LPVOID User);
int ChebTCPServerSocket::StartServer()
{
    if(PORT==0){return -1;}
    WSADATA *WsaData;
    if(WSAStartup(0x202,WsaData))
    ServerSocket=socket(AF_INET,SOCK_STREAM,0);
    if(ServerSocket==INVALID_SOCKET){return -2;}
    sockaddr_in ServerAddr;
    ServerAddr.sin_family=AF_INET;
    ServerAddr.sin_port=htons(PORT);
    ServerAddr.sin_addr.s_addr=0;
    if(bind(ServerSocket,(sockaddr *)&ServerAddr,sizeof(ServerAddr))!=0)
    {return -3;}
    if(listen(ServerSocket,0x100))
    {return -4;}
    ServerActive=true;
    CreateThread(0,0,&ClientAccept,0,0,0);
    return 0;
}
//------------------------------------------------------------------------------
DWORD WINAPI ChebTCPServerSocket::ClientAccept(LPVOID Nothing)
{
    sockaddr ClientAddr;
    int ClientAddrSize=sizeof(ClientAddr);
    int Id;
    while((TempSocket=accept(ServerSocket,&ClientAddr,&ClientAddrSize))&&ServerActive==true)
    {
        COUNT++;
        User=new UserOnline;
        HOSTENT *hst;
        hst=gethostbyname((char*)&ClientAddr);
 
        for(Id=0;Id<sizeof(User);Id++)
        {
            if(User[Id].ID==0&&User[Id].IDOnline==0&&User[Id].IP=="")
            {
                strcat(User[Id].IP,(char*)&ClientAddr);
                User[Id].IDOnline=Id;
                break;
            }
        }
    CreateThread(0,0,&ClientThread,&User[Id],0,0);
    }
}
//------------------------------------------------------------------------------
    DWORD WINAPI ChebTCPServerSocket::ClientThread(LPVOID User)
    {
        UserOnline *Usermem;
        Usermem=(UserOnline *)User;
        char buff[BUFFSIZE];
        while(int SizeRecv=recv(Usermem->UserSocket,buff,BUFFSIZE,0)&&SizeRecv==INVALID_SOCKET)
        {}
        delete Usermem;
    }
//------------------------------------------------------------------------------



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

дубль два

Цитата
Сообщение от retmas
Посмотреть сообщение

ClientAccept и ClientThread должны возвращать значения.

Добавлено через 53 секунды
добавьте, например, return 0; в них
перестройте проект. если есть ошибки — в студию



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

user2891869's user avatar

user2891869user2891869

5691 gold badge4 silver badges12 bronze badges

3

  • You forgot to add #endif at the end

    Oct 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 Velleman's user avatar

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

Понравилась статья? Поделить с друзьями:
  • Unsupported stream type hikvision как исправить ошибку
  • Upsmon pro ошибка соединения usb
  • Updater симс 4 ошибка
  • Unsupported command 7 zip ошибка
  • Urctbased dll ошибка