Ошибка variable or field declared void

I have a function called:

void initializeJSP(string Experiment)

And in my MyJSP.h file I have:

2: void initializeJSP(string Experiment);

And when I compile I get this error:

MyJSP.h:2 error: variable or field initializeJSP declared void

Where is the problem?

jonsca's user avatar

jonsca

10.2k26 gold badges54 silver badges62 bronze badges

asked Dec 12, 2008 at 21:31

Eduardo's user avatar

1

It for example happens in this case here:

void initializeJSP(unknownType Experiment);

Try using std::string instead of just string (and include the <string> header). C++ Standard library classes are within the namespace std::.

answered Dec 12, 2008 at 21:36

Johannes Schaub - litb's user avatar

1

This is not actually a problem with the function being «void», but a problem with the function parameters. I think it’s just g++ giving an unhelpful error message.

EDIT: As in the accepted answer, the fix is to use std::string instead of just string.

answered Sep 26, 2011 at 6:36

Paul Price's user avatar

Paul PricePaul Price

2,64729 silver badges26 bronze badges

1

or like in my case the solution was just to declare the fitting header in the main.cpp instead of the header in the function.cpp, trying to include that one..

#include"header.h" //instead of "function.cpp"
int main() 

and in function.cpp

#include"header.h"
void ()

this way compiling and linking just works fine …

ewertonvsilva's user avatar

answered Dec 13, 2021 at 16:13

barpe's user avatar

The thing is that, when you call a function you should not write the type of the function, that means you should call the funnction just like

initializeJSP(Experiment);

Brighter side's user avatar

answered May 13, 2017 at 23:25

Daniel Montaña's user avatar

3

Other answers have given very accurate responses and I am not completely sure what exactly was your problem(if it was just due to unknown type in your program then you would have gotten many more clear cut errors along with the one you mentioned) but to add on further information this error is also raised if we add the function type as void while calling the function as you can see further below:

#include<iostream>
#include<vector>
#include<utility>
#include<map>
using namespace std;
void fun(int x);
main()
{
   int q=9;
   void fun(q); //line no 10
}
void fun(int x)
{
    if (x==9)
        cout<<"yes";
    else
        cout<<"no";
}

Error:

 C:UsersACERDocumentsC++ programsexp1.cpp|10|error: variable or field 'fun' declared void|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

So as we can see from this example this reason can also result in «variable or field declared void» error.

answered Jun 21, 2018 at 15:05

RSSB's user avatar

RSSBRSSB

1442 gold badges4 silver badges14 bronze badges

1

Did you put void while calling your function?

For example:

void something(int x){
    logic..
}

int main() {

    **void** something();

    return 0;

}

If so, you should delete the last void.

Pika Supports Ukraine's user avatar

answered Apr 12, 2019 at 19:47

user11353491's user avatar

Начал изучать подпрограммы (функции) и приехали…

Offline

Зарегистрирован: 04.12.2015

Всем, здравствуйте!

Начал изучать функции и…

В общем, не подскажете, почему не работает вот это?

int k=20;
int e;
int r;


void setup()
{
}


void fun(r) // функция (подпрограмма)
{
   e=r+1;
}



void loop()
{
   fun(k);
}

Ругается что-то в этом роде:

error: variable or field ‘fun’ declared void

‘fun’ was not declared in this scope

    fun(k);

         ^

exit status 1
variable or field ‘fun’ declared void

Замена типа функции «fun» с void на int (или любой другой) ничего не дает (мне, в принципе, нужен void). Стоит убрать аргументы (т.е. чтобы в скобках было пусто), все работает с любым типом функции.

Я, конечно понимаю, что вопрос идиотский, но что здесь не так? Никак не въеду… Подскажите новичку.

Спасибо!

Arduino Forum

Loading

For a larger sketch, I have separated a chunk of code in a separate .cpp file

#include "msg.h"
#include <Arduino.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv)
{


    String json = payload;

    // Serial.println(json); // enable to debug

    StaticJsonDocument<128> filter;

    JsonObject filter_current = filter.createNestedObject("current");
    filter_current["temp_c"] = true;
    filter_current["wind_mph"] = true;
    filter_current["pressure_mb"] = true;
    filter_current["precip_in"] = true;
    filter_current["humidity"] = true;
    filter_current["feelslike_c"] = true;
    filter_current["uv"] = true;

    StaticJsonDocument<256> doc;

    // Deseriliaze and display error description if there is any
    DeserializationError error = deserializeJson(doc, json, DeserializationOption::Filter(filter));

    if (error)
    {
        Serial.print("deserializeJson() failed: ");
        Serial.println(error.c_str());
        return;
    }

    JsonObject current = doc["current"];
    temp = current["temp_c"];          // 80
    wind = current["wind_mph"];        // 5.6
    pressure = current["pressure_mb"]; // 1005
    humid = current["humidity"];       // 93
    feel = current["feelslike_c"];     // 6.9
    uv = current["uv"];                // 1
}

together with its header file as below:

#ifndef MSG_H
#define MSG_H

void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);

#endif

I have included all the relevant libraries in the .cpp files. However, when I try to compile the code I get multiple errors such as

In file included from src/weatherapi.cpp:1:0:
include/weatherapi.h:4:17: error: variable or field 'getRequest' declared void
 void getRequest(String &payload);
                 ^
include/weatherapi.h:4:17: error: 'String' was not declared in this scope
include/weatherapi.h:4:25: error: 'payload' was not declared in this scope
 void getRequest(String &payload);
                         ^
Archiving .piobuildlolin32liba47libPubSubClient.a
In file included from src/msg.cpp:1:0:
include/msg.h:4:20: error: variable or field 'parseResponse' declared void
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                    ^
include/msg.h:4:20: error: 'String' was not declared in this scope
include/msg.h:4:28: error: 'payload' was not declared in this scope
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                            ^
include/msg.h:4:37: error: expected primary-expression before 'float'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                                     ^
include/msg.h:4:50: error: expected primary-expression before 'float'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                                                  ^
include/msg.h:4:63: error: expected primary-expression before 'int'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                                                               ^
include/msg.h:4:78: error: expected primary-expression before 'int'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                                                                              ^
include/msg.h:4:90: error: expected primary-expression before 'float'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                                                                                          ^
include/msg.h:4:103: error: expected primary-expression before 'int'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);

The function parseResponse doesn’t return anything so I don’t know why it’s complaining about being declared as void. Same is true for the function getRequest. Also, is there something wrong in the function prototype as I am passing references?

Edit: Here is the weatherapi.cpp & .h file

#include "weatherapi.h"
#include <HTTPClient.h>
#include <Arduino.h>

const char url[] = "http://api.weatherapi.com/v1/current.json?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

void getRequest(String &payload)
{

     HTTPClient getClient;

    getClient.begin(url);

   
    int httpCode = getClient.GET();

    //get response and check HTTP status code returned
    if (httpCode > 0)
    {
        payload = getClient.getString();
        Serial.print("HTTP Status: ");
        Serial.println(httpCode);
    }
    else
    {
        Serial.println("Error on HTTP request");
    }
   
    getClient.end();
} 

weatherapi.h file

#ifndef WEATHERAPI_H
#define WEATHERAPI_H

void getRequest(String &payload);
#endif

                                                                                             

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
#include <stdio.h>
void probel(FILE*,FILE*);
void tire(char,FILE*,FILE*);
void znak(char,FILE*,FILE*);
void prov(char,FILE*,FILE*);
    int main()
    {
        FILE *f1,*f2;
        char c,x;
        
        if((f1= fopen("text.txt","r"))==NULL)
        {perror("Ошибка открытия файла");
        return 1;
        }
        
        if((f2= fopen("new.txt","w"))==NULL)
        {perror("Ошибка создания файла");
        return 1;
        }
        
        while((c=fgetc(f1))!=EOF)
        {
        switch (c)
        {
        case ' ':probel(f1,f2);break;
        case '-':tire(c,f1,f2);break;
        case '.':znak(c,f1,f2);break;
        case ',':znak(c,f1,f2);break;
        case '!':znak(c,f1,f2);break;
        case '?':znak(c,f1,f2);break;
        case ')':znak(c,f1,f2);break;
        case '(':znak(c,f1,f2);break;
        default :fputc(c,f2);
        }
        }
    
    fclose(f1);
    fclose(f2);
 
    return 0;
    }
    
    void probel (*f1,*f2)
    {char c
    if((c=fgetc(f1))!=EOF&&c!=','&&c!='.'&&c!='!'&&c!='?'&&c!='.'&&c!=')'&&c!='(')
        {fputc(" ",f2);if(c!=' ') proverka(c,f1,f2);}
        return;
    }
    void tire(c,*f1,*f2)
    {
        char c;
        fputc(c,f2);
        if((c=fgetc(f1))!=EOF&&c!='-') proverka(c,f1,f2) ; else if(c!=EOF){fputs("-",f2);prov((c=fgetc(f1)),f1,f2);}
        return;
    }
    
    void znak(c,f1,f2)
    {   
        fpurc(c,f2);
        if((c=fgetc(f1))!=EOF&&c!=' ') fputc(" ",f2);else if(c!=EOF)proverka((c=fgetc(f1)),f1,f2) ;   
        
        return; 
    }
    
    void prov(c,*f1,*f2);
        {
        switch c
        {
        case ' ':probel(c,f1,f2);break;
        case '-':tire(c,f1,f2);break;
        case '.':znak(c,f1,f2);break;
        case ',':znak(c,f1,f2);break;
        case '!':znak(c,f1,f2);break;
        case '?':znak(c,f1,f2);break;
        case ')':znak(c,f1,f2);break;
        case '(':znak(c,f1,f2);break;
        default fputc(c,*f2);
        }
        return;
        }

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Ошибка variable identifier expected
  • Ошибка vanos выпуск n20
  • Ошибка vanos впуск n52
  • Ошибка van9001 valorant

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии