Error list was not declared in this scope

I am new to c++, and I am trying to get a basic program to initialize a list of short unsigned integers. I am compiling and running using scygwin and g++. Below is the code in the .cpp file: #inc...

using namespace std; doesn’t add any functionality to your code. It just means you don’t have to type std:: when referencing things in the std namespace, like std::list.

To actually include the code base for std::list into your program, you need to add:

#include <list>

When in doubt about this kind of thing, doing a google search for cpp reference list will turn up a page like this where you can see: Defined in header <list> at the top.

Here’s another question about using namespace std; that may prove useful and why you shouldn’t use it. I’ll add a little bit to perhaps explain namespaces.

It is common in C++ programs to organize functions into classes and namespaces. Imagine you wrote your own list class to handle certain scenarios. In order to prevent naming conflicts you would put it in a different namespace than std.

namespace MyApp {
    class list;
    void sort(list&);
}

For the majority of a large code base you might still prefer to use std::list but you need MyApp::list for some things. Using namespaces you can cluster your code and prevent naming conflicts for similar functionality.

Summary

using namespace std; makes it so that if you reference a function or class not in the global namespace it looks for it in the std namespace.

#include <list> actually inserts prototypes (information about how to access the code) in your source file during the preprocessor stage.

SergeyKagen

3 / 4 / 2

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

Сообщений: 315

1

19.04.2019, 22:16. Показов 131712. Ответов 14

Метки нет (Все метки)


Простой код, но Arduino IDE напрочь отказывается принимать переменные. Что за глюк или я что-то неправильно делаю?

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void setup() {
  
  Serial.begin(9600);
  int count = 0;
  pinMode(7, INPUT);
  pinMode(13, OUTPUT);
 
}
 
void loop() {
 
  if( digitalRead(7) == HIGH ){ 
    
    while(1){ 
      delayMicroseconds(2); 
      count++;  
      if( digitalRead(7) == LOW ){ Serial.println(count); count = 0; break; }
      }
    }  
}

ошибка при компиляции «‘count’ was not declared in this scope», что не так?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



marat_miaki

495 / 389 / 186

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

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

19.04.2019, 23:26

2

Лучший ответ Сообщение было отмечено SergeyKagen как решение

Решение

C++
1
2
3
4
5
6
7
8
  int count = 0; //глобальная переменная
 
  void setup() {
   Serial.begin(9600);
  pinMode(7, INPUT);
  pinMode(13, OUTPUT);
 
}



1



Lavad

0 / 0 / 0

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

Сообщений: 25

14.09.2019, 22:33

3

Доброго времени суток!
У меня то же сообщение, но на функцию :-(
Создал функцию (за пределами setup и loop), которая только принимает вызов, ничего не возвращает:

C++
1
2
3
4
5
void myDispay(byte x, byte y, char str) {
  lcd.setCursor(x, y);
  lcd.print(temp, 1);   // выводим данные, с точностью до 1 знака после запятой
  lcd.print(str);   // выводим писанину
  }

В loop() делаю вызов:

C++
1
myDisplay(0,0,"C");

При компиляции выделяется этот вызов, с сообщением:

‘myDisplay’ was not declared in this scope

Замучился искать инфу о декларации/обьявлении функции. Везде, что находил, понимал одно: если ты вызываешь функцию, это и есть обьявление функции
Что делаю не так? В чем моя ошибка? Помогите, пожалуйста.

P.S. Код, что использовал в качестве функции, работоспособен. Раньше находился в loop(). Скетч постепенно разрастается, много однотипных обращений к дисплею…



0



Эксперт С++

8385 / 6147 / 615

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

Сообщений: 28,683

Записей в блоге: 30

14.09.2019, 23:57

4

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

Создал функцию (за пределами setup и loop),

Перевидите на нормальный язык.
Какие еще пределы?

В другом файле что ли?

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

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

Замучился искать инфу о декларации/обьявлении функции. Везде, что находил, понимал одно: если ты вызываешь функцию, это и есть обьявление функции
Что делаю не так? В чем моя ошибка? Помогите, пожалуйста

Читать учебники по С++ не пробовали?

https://metanit.com/cpp/tutorial/3.1.php
http://cppstudio.com/post/5291/

Специфика Arduino лишь отличается тем что пред объявления не всегда нужны.

Добавлено через 7 минут
Кроме того иногда потеряй скобок {} приводят к таким ошибкам.



0



ValeryS

Модератор

Эксперт по электронике

8759 / 6549 / 887

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

Сообщений: 22,972

15.09.2019, 00:09

5

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

Везде, что находил, понимал одно: если ты вызываешь функцию, это и есть обьявление функции

это где ж такое написано?
функцию нужно объявить перед первым вызовом, сиречь сверху
можно и просто декларировать сверху

C++
1
void myDispay(byte x, byte y, char str);

а объявить уже в удобном месте



0



0 / 0 / 0

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

Сообщений: 25

15.09.2019, 00:48

6

Неделю назад ВПЕРВЫЕ включил Arduino Uno.
Задолго до этого писал программы под Windows (БейсикВизуал) и AVR (Basic, немного Assembler). Т.е. имеется некоторое представление об объявлении переменных, функций,… От Си всегда держался как можно дальше. Это первая и последняя причина «нечитания» книг по Си. За неделю экспериментов на Arduino мнение об этом пока не изменилось — легче вернуться к Ассму, чем копаться в Си.

Написал на том же языке, что и читал на всяких форумах и справочниках по Arduino :-). За пределами этих функций — значит не внутри них.

Обе приведенных Вами ссылок просмотрел, проверил в скетче… В итоге вылезла другая ошибка:
function ‘void myDisplay(byte, byte, char)’ is initialized like a variable

void myDisplay(byte x, byte y, char str) тоже пробовал. Та же ошибка.

Что не так на этот раз? :-(



0



Модератор

Эксперт по электронике

8759 / 6549 / 887

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

Сообщений: 22,972

15.09.2019, 01:26

7

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

В итоге вылезла другая ошибка:
function ‘void myDisplay(byte, byte, char)’ is initialized like a variable

точку с запятой в конце поставил?



1



Lavad

0 / 0 / 0

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

Сообщений: 25

15.09.2019, 08:46

8

Вот скетч. Проще некуда.

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
#include <PCD8544.h>
 
float temp = 0;
static PCD8544 lcd;   // даем имя подключенному дисплею (lcd)
static const byte Lm35Pin = 14;   // аналоговый пин (A0) Arduino, к которому подключен LM35
 
//void myDisplay() = 0;
//void myDisplay(byte, byte, char, float) = 0;
//void myDisplay(byte x, byte y, char str, float temp) = 0;
 
void myDispay(byte x, byte y, char str, float temp) {
  lcd.setCursor(x, y);   // начиная с (x,y)...
  lcd.print(temp, 1);   // выводим temp
  lcd.print(str);   // выводим писанину
}
 
void setup() {
  lcd.begin(84, 48);   // инициализируем дисплей
  analogReference(INTERNAL);   // подключаем внутренний ИОН на 1.1V
}
 
void loop() {
  float temp = analogRead(Lm35Pin) / 9.31;  // подсчитываем температуру (в Цельсиях)...
  myDisplay(0, 0, "C", temp);   // отправляем данные на экран
  delay(500);   // ждем 500 мсек
}

Любое из трех так называемых «объявлений» (строки 7…9) выдает одну и ту же ошибку — я пытаюсь объявить функцию как переменную.

Добавлено через 9 минут
Попробовал так:

C++
1
void myDisplay(byte x, byte y, char str, float temp);

Компилятор задумался (я успел обрадоваться), но, зараза :-), он снова поставил свой автограф :-)

undefined reference to `myDisplay(unsigned char, unsigned char, char, float)

На этот раз он пожаловался на строку вызова функции.

Добавлено через 34 минуты
Когда что-то новое затягивает, забываешь о нормальном отдыхе, теряешь концентрацию…
Нашел ошибку. Чистейшая грамматика

C++
1
void myDispay(byte x,...

Dispay вместо Display

Добавлено через 8 минут
ValeryS, благодарю за попытку помощи!



0



ValeryS

Модератор

Эксперт по электронике

8759 / 6549 / 887

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

Сообщений: 22,972

15.09.2019, 10:36

9

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

void myDisplay(byte, byte, char, float) = 0;

вот так не надо делать(приравнивать функцию к нулю)
так в классическом С++ объявляют чисто виртуальные функции, и класс в котором объявлена чисто виртуальная функция становится абстрактным. Означает что у функции нет реализации и в дочернем классе нужно обязательно реализовать функцию. А из абстрактного класса нельзя создать объект

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

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

void myDispay(byte x, byte y, char str, float temp)

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

myDisplay(0, 0, «C», temp);

просишь чтобы функция принимала символ char str, а передаешь строку "C"
или передавай символ

C++
1
myDisplay(0, 0, 'C', temp);

или проси передавать строку, например так

C++
1
void myDispay(byte x, byte y, char * str, float temp);



1



Avazart

Эксперт С++

8385 / 6147 / 615

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

Сообщений: 28,683

Записей в блоге: 30

15.09.2019, 12:02

10

Кроме того наверное лучше так:

C++
1
2
3
4
5
6
7
8
void myDispay(PCD8544& lcd,byte x, byte y, char str, float temp) 
{
  lcd.setCursor(x, y);   // начиная с (x,y)...
  lcd.print(temp, 1);   // выводим temp
  lcd.print(str);   // выводим писанину
}
 
myDisplay(lcd,0, 0, 'C', temp);

Тогда можно будет вынести ф-цию в отдельный файл/модуль.



1



locm

15.09.2019, 21:07

Не по теме:

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

Arduino Uno.

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

AVR (Basic, немного Assembler).

Arduino Uno это AVR, для которого можете писать на бейсике или ассемблере.



0



Avazart

15.09.2019, 21:21

Не по теме:

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

Arduino Uno это AVR, для которого можете писать на бейсике или ассемблере.

Но лучше не надо …



0



Lavad

0 / 0 / 0

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

Сообщений: 25

16.09.2019, 12:12

13

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

это где ж такое написано?
функцию нужно объявить перед первым вызовом, сиречь сверху
можно и просто декларировать сверху
а объявить уже в удобном месте

Оказалось, что я верно понял чтиво по справочникам: если ты вызываешь функцию, это и есть обьявление функции. А сама функция может располагаться по скетчу в ЛЮБОМ месте (но за пределами setup, loop и любых других функций). И больше никаких специфических строк.

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

вот так не надо делать(приравнивать функцию к нулю)…

Методом проб и ошибок уже понял :-).

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

или передавай символ… 'C'

Если передаю в одинарных кавычках

более одного

символа, а функция ждет как char str, то выводятся на экран только самый правый из отправленных символов. Отправил «абв», а выводится «в».
Выкрутился, прописав в функции char str[], а символы отправляю через двойные кавычки.

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

или проси передавать строку, например так… char * str

Буквально вчера попалось это в справочнике, но как-то не дошло, что тоже мой вариант :-).

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

Кроме того наверное лучше так:

C++
1
void myDispay(PCD8544& lcd,byte x, byte y, char str, float temp) {...}

Тогда можно будет вынести ф-цию в отдельный файл/модуль.

Благодарю за совет! Как-нибудь проверю…



0



Эксперт С++

8385 / 6147 / 615

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

Сообщений: 28,683

Записей в блоге: 30

16.09.2019, 12:54

14

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

Оказалось, что я верно понял чтиво по справочникам: если ты вызываешь функцию, это и есть обьявление функции

Нафиг выкиньте эти справочники.
Почитайте мои ссылки.



0



0 / 0 / 0

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

Сообщений: 25

16.09.2019, 13:00

15

Ссылки Ваши добавлены в закладки. Время от времени заглядываю.
Но теория для меня — всего лишь набор понятий. Я же высказался после практической проверки. А как я понял, так оно и работает :-)



0



  1. 08-26-2007


    #1

    DarrenY is offline


    Registered User


    Class not declared in the scope

    Hi,

    I’m running into trouble here as I’m programming C++ with QT4.3.

    Here’s a snippet

    Code:

    #Asteroid.h
    #ifndef ASTEROID_H
    #define ASTEROID_H
    #include <QPainter>
    #include "AsteroidList.h"
    
    class Asteroid
    {
    
      public:
        Asteroid() { AsteroidList list; }
        void addAsteroid(int,int,int);
        void displayAsteroid();
        void draw(QPainter&);
    };
    #endif

    Code:

    #AsteroidList.h
    #ifdef ASTEROIDLIST_H
    #define ASTEROIDLIST_H
    
    #include <QPainter>
    #include "AsteroidNode.h"
    
    class AsteroidList
    {
       public:
         AsteroidList();
         Asteroid* first;
         void addAsteroid(int,int,int);
         void drawAsteroid(QPainter&);
         void display();
       private:
         AsteroidNode* a_first;
    };
    #endif

    Code:

    #AsteroidList.cpp
    #include "AsteroidList.h"
    #include <iostream>
    
    //Default Constructor
    AsteroidList::AsteroidList()
      {
        a_first = NULL;
      }

    As I compile with QT4.3, I encountered this error
    Asteroid.h: In constructor ‘Asteroid::Asteroid()’:
    Asteroid.h:15: error: ‘AsteroidList’ was not declared in this scope
    Asteroid.h:15: error: expected `;’ before ‘list’
    Asteroid.cpp: In member function ‘void Asteroid::addAsteroid(int, int, int)’:
    Asteroid.cpp:13: error: ‘list’ was not declared in this scope
    Asteroid.cpp: In member function ‘void Asteroid::displayAsteroid()’:
    Asteroid.cpp:19: error: ‘list’ was not declared in this scope
    Asteroid.cpp: In member function ‘void Asteroid::draw(QPainter&)’:
    Asteroid.cpp:25: error: ‘list’ was not declared in this scope

    What i’m concerned is, why is the AsteroidList class not detected in Asteroid.h file even if I’ve included them?

    Please help.

    P.S. The codes are incomplete as I’m focusing only on why the class name is not there.


  2. 08-26-2007


    #2

    Daved is offline


    Registered User


    >> #AsteroidList.h
    I hope that’s not actually in your file. If you want to have the name of the file in the file, use:>> #ifdef ASTEROIDLIST_H
    That should be #ifndef, not #ifdef. I think this is causing your first error (and probably others).

    You are going to need a forward declaration for Asteroid in your AsteroidList.h file. Put this just below the includes:


  3. 08-27-2007


    #3

    ZuK is offline


    Registered User


    Quote Originally Posted by Daved
    View Post

    >>
    You are going to need a forward declaration for Asteroid in your AsteroidList.h file. Put this just below the includes:

    In addition to that you will have to change the constructor of Asteroid to take either a pointer or a reference to an AsteroidList.

    Quote Originally Posted by DarrenY

    What i’m concerned is, why is the AsteroidList class not detected in Asteroid.h file even if I’ve included them?

    That is because when including AsteoidList.h, AsteroidList.h includes Asteroid.h but then ASTEROIDLIST_H is already defined and AsteroidList.h will not be read anymore -> class AstreoidList is undefined for class Asteroid.

    Kurt


  4. 08-27-2007


    #4

    anon is offline


    The larch


    It is questionable, though, why an Asteroid would need to declare a local AsteroidList in its constructor. And if it is just a simplified example, still — does a single Asteroid need to know anything about the AsteroidList (and other Asteroids) or should it function on its own and let something else handle the interactions (e.g collisions)?

    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.

    Quoted more than 1000 times (I hope).


  5. 08-27-2007


    #5

    Daved is offline


    Registered User


    >> In addition to that you will have to change the constructor of Asteroid to take either a pointer or a reference to an AsteroidList.

    I don’t think that’s necessary. Asteroid can know about AsteroidList and include the definition of that class as long as AsteroidList only requires a forward declaration of Asteroid and doesn’t need to include its full definition.


  6. 08-27-2007


    #6

    ZuK is offline


    Registered User


    Quote Originally Posted by Daved
    View Post

    >> In addition to that you will have to change the constructor of Asteroid to take either a pointer or a reference to an AsteroidList.

    I don’t think that’s necessary. Asteroid can know about AsteroidList and include the definition of that class as long as AsteroidList only requires a forward declaration of Asteroid and doesn’t need to include its full definition.

    Yes. Shure.
    My excuse is just that I read this

    Code:

        Asteroid() { AsteroidList list; }

    as a constructor that takes an AsteroidList as parameter (should have noticed that it makes little sense to pass a list by value ) and then got it all wrong.
    Next time I’ll activate brains before posting.
    Kurt


  7. 08-27-2007


    #7

    Daved is offline


    Registered User


    >> I read this as a constructor that takes an AsteroidList as parameter

    Oops. I actually read it the same way both times I looked at it, too.


#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <sys/socket.h>
#include <sys/unistd.h>
#include <sys/types.h>
#include <sys/errno.h>
#include <netinet/in.h>
#include <signal.h>
#include <iostream>
#include <thread>

using namespace std;

#define BUFFSIZE 2048
#define DEFAULT_PORT 4001    //
#define MAXLINK 2048

void connecter()
{
    printf("Listening...n");
    while (true)
    {
        signal(SIGINT, stopServerRunning);    // 
        // 
        connfd = accept(sockfd, NULL, NULL);
        if (-1 == connfd)
        {
            printf("Accept error(%d): %sn", errno, strerror(errno));
            return -1;
        }
    }
}

void listener()
{
    while(true)
    {
        bzero(buff, BUFFSIZE);
        //
        recv(connfd, buff, BUFFSIZE - 1, 0);
        // 
        printf("клиент: %sn", buff);
        //
        send(connfd, buff, strlen(buff), 0);
    }
}

void sender()
{
    while(true)
    {
        printf("Please input: ");
        scanf("%s", buff);
        send(connfd, buff, strlen(buff), 0);
        bzero(buff, sizeof(buff));
        recv(connfd, buff, BUFFSIZE - 1, 0);
        printf("recv: %sn", buff);
    }
}

int sockfd, connfd; 
void stopServerRunning(int p)
{
    close(sockfd);
    printf("Close Servern");
    exit(0);
}
int main()
{
    struct sockaddr_in servaddr;
    char buff[BUFFSIZE];
    //
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == sockfd)
    {
        printf("Create socket error(%d): %sn", errno, strerror(errno));
        return -1;
    }
    // 
    // 
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(DEFAULT_PORT);
    if (-1 == bind(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)))
    {
        printf("Bind error(%d): %sn", errno, strerror(errno));
        return -1;
    }
    // 
    //
    if (-1 == listen(sockfd, MAXLINK))
    {
        printf("Listen error(%d): %sn", errno, strerror(errno));
        return -1;
    }
    
    while(true)
    {
        thread my_thread(connecter);
        if(connfd == true)
            break;
    }

    thread my_thread(connecter);
    thread my_thread(listener);
    thread my_thread(sender);

    return 0;
}

}

это исходный код программы, хотел написать что-то вроде чата на сокетах. Я попытался скомпилировать код, но он мне выдал несколько ошибок «was not declared in this scope». Вот вывод компилятора:

server.cpp: In function ‘void connecter()’:
server.cpp:24:24: error: ‘stopServerRunning’ was not declared in this scope
   24 |         signal(SIGINT, stopServerRunning);    // Это предложение используется для выключения сервера при вводе Ctrl + C
      | 

server.cpp:26:9: error: ‘connfd’ was not declared in this scope
   26 |         connfd = accept(sockfd, NULL, NULL);
      |         ^~~~~~

server.cpp:26:25: error: ‘sockfd’ was not declared in this scope; did you mean ‘socket’?
   26 |         connfd = accept(sockfd, NULL, NULL);
      |                         ^~~~~~
      |                         socket

server.cpp: In function ‘void listener()’:
server.cpp:39:15: error: ‘buff’ was not declared in this scope
   39 |         bzero(buff, BUFFSIZE);
      |               ^~~~

server.cpp:41:14: error: ‘connfd’ was not declared in this scope
   41 |         recv(connfd, buff, BUFFSIZE - 1, 0);
      |              ^~~~~~

server.cpp: In function ‘void sender()’:
server.cpp:54:21: error: ‘buff’ was not declared in this scope
   54 |         scanf("%s", buff);
      |                     ^~~~

server.cpp:55:14: error: ‘connfd’ was not declared in this scope
   55 |         send(connfd, buff, strlen(buff), 0);
      |              ^~~~~~

я думаю, что все эти ошибки идут из одной проблемы, но не могу понять откуда

Arduino programming is an open-source and simple stage that arranges the Arduino board into working with a particular goal in mind. An Arduino code is written in C++ yet with extra capacities and strategies. An Arduino is an equipment and programming stage broadly utilised in hardware.

In this article, we go through three quick fixes for the error ‘was not declared in this scope’.

Also read: How to solve the Tower of Hanoi problem using Python?


What does the error mean?

Every programming language has a concept of Scope. Scope tells us where a specific variable, constant or function is accessible and usable. It refers to the area of code a statement, block, or name. The scope of an entity determines where that entity is usable in other parts of the program. The scope of a block determines where that block can be used in other blocks, and the scope of a name determines where that name can be used in other names.

There are two types of scope in programming languages: local and global. Local scope refers to the identifiers and symbols visible inside a block of code. Global scope, on the other hand, refers to the identifiers and symbols visible outside a block of code.

The error ‘was not declared in this scope’ generally occurs when a variable or function is not accessible to its call. A global variable in Arduino is the variable that is declared outside any function, including the setup() and loop() functions. Any variable declared inside a function or loop has restrictive access and is a local variable.

If any other function calls a local variable, it gives an error. To call any variable or function in any other function, including the setup() and loop() function, it should be declared as a global variable.

Also read: How to stop an Arduino program?


There are the quick fixes for the Arduino error: was not declared in the scope.

Declare the variable

Before assigning a value to the variable, make sure to define it. There are 16 data types commonly used in Arduino coding. Each data type expresses the nature of the value assigned to it. If the data type and value doesn’t match, an error arises. Also, if a variable is assigned any value without its declaration or data type, the error occurs.

Always ensure to declare the variable before the assignment. There are two ways to do this.

How to solve Arduino error: 'was not declared in this scope'?

There are three variables in the above example – num1, num2 and num3. The variable num1 has been declared separately and assigned to a data type corresponding value in the loop. The variable num2 has been declared and assigned in the same line of code. The variable num3, on the other hand, has directly been assigned a value without its declaration. This causes the error, as shown above.


Other details

There may be errors arising even after proper declaration and assignment of the variable. This may be due to incorrect or absence of the closing brackets, semicolons or improper declaration of functions. Ensure proper use of syntax when defining loops and functions. Every opening in curly brace must be accounted for and closed. Extra closing braces also cause errors. Alongside, semicolons hold their importance. A semicolon missed can cause the entire program to go haywire.


Library folder

Many times, variables call or use functions that require importing a few specific libraries.

How to solve Arduino error: 'was not declared in this scope'?

In the example above, the variable num calls the square root function – sqrt() from the maths library of Arduino. If we call a function without including its library first, an error occurs. There are multiple inbuilt and standard libraries in Arduino, while a few special libraries must be included separately.

Also read: What is ‘does not name a type’ in Arduino: 2 Fixes.

Example

This error happens if a unknown object is used.

Variables

Not compiling:

#include <iostream>

int main(int argc, char *argv[])
{
    {
        int i = 2;
    }

    std::cout << i << std::endl; // i is not in the scope of the main function

    return 0;
}

Fix:

#include <iostream>

int main(int argc, char *argv[])
{
    {
        int i = 2;
        std::cout << i << std::endl;
    }

    return 0;
}

Functions

Most of the time this error occurs if the needed header is not
included (e.g. using std::cout without #include <iostream>)

Not compiling:

#include <iostream>

int main(int argc, char *argv[])
{
    doCompile();

    return 0;
}

void doCompile()
{
    std::cout << "No!" << std::endl;
}

Fix:

#include <iostream>

void doCompile(); // forward declare the function

int main(int argc, char *argv[])
{
    doCompile();

    return 0;
}

void doCompile()
{
    std::cout << "No!" << std::endl;
}

Or:

#include <iostream>

void doCompile() // define the function before using it
{
    std::cout << "No!" << std::endl;
}

int main(int argc, char *argv[])
{
    doCompile();

    return 0;
}

Note: The compiler interprets the code from top to bottom (simplification). Everything must be at least declared (or defined) before usage.

Tips: If you need C++ homework help from experts, you can always rely upon assignment helpers.

Error message 'dir1PinL' was not declared in this scope. keeps coming up. Any ideas?

#include "Arduino.h"

/*motor control*/
void go_Advance(void)  //Forward
{
  digitalWrite(dir1PinL, HIGH);
  digitalWrite(dir2PinL, LOW);
  digitalWrite(dir1PinR, HIGH);
  digitalWrite(dir2PinR, LOW);
}

void go_Left(void)  //Turn left
{
  digitalWrite(dir1PinL, HIGH);
  digitalWrite(dir2PinL, LOW);
  digitalWrite(dir1PinR, LOW);
  digitalWrite(dir2PinR, HIGH);
}

void go_Right(void)  //Turn right
{
  digitalWrite(dir1PinL, LOW);
  digitalWrite(dir2PinL, HIGH);
  digitalWrite(dir1PinR, HIGH);
  digitalWrite(dir2PinR, LOW);
}

void go_Back(void)  //Reverse
{
  digitalWrite(dir1PinL, LOW);
  digitalWrite(dir2PinL, HIGH);
  digitalWrite(dir1PinR, LOW);
  digitalWrite(dir2PinR, HIGH);
}

void stop_Stop()    //Stop
{
  digitalWrite(dir1PinL, LOW);
  digitalWrite(dir2PinL, LOW);
  digitalWrite(dir1PinR, LOW);
  digitalWrite(dir2PinR, LOW);
}

/*set motor speed */
void set_Motorspeed(int speed_L, int speed_R)
{
  analogWrite(speedPinL, speed_L);
  analogWrite(speedPinR, speed_R);
}

//Pins initialize
void init_GPIO()
{
  pinMode(dir1PinL, OUTPUT);
  pinMode(dir2PinL, OUTPUT);
  pinMode(speedPinL, OUTPUT);

  pinMode(dir1PinR, OUTPUT);
  pinMode(dir2PinR, OUTPUT);
  pinMode(speedPinR, OUTPUT);
  stop_Stop();
}

void setup()
{
  init_GPIO();
  go_Advance();//Forward
  set_Motorspeed(255, 255);
  delay(5000);

  go_Back();//Reverse
  set_Motorspeed(255, 255);
  delay(5000);

  go_Left();//Turn left
  set_Motorspeed(255, 255);
  delay(5000);

  go_Right();//Turn right
  set_Motorspeed(255, 255);
  delay(5000);

  stop_Stop();//Stop
}

void loop()
{
}

This is the entire error message:

Arduino: 1.8.6 (Windows 10), Board: "Arduino/Genuino Uno"

C:UsersWilliamDocumentssmartcar-lesson1smartcar-lesson1.ino: In function 'void go_Advance()':

smartcar-lesson1:20:16: error: 'dir1PinL' was not declared in this scope

   digitalWrite(dir1PinL, HIGH);

                ^

smartcar-lesson1:21:16: error: 'dir2PinL' was not declared in this scope

   digitalWrite(dir2PinL,LOW);

                ^

smartcar-lesson1:22:16: error: 'dir1PinR' was not declared in this scope

   digitalWrite(dir1PinR,HIGH);

                ^

smartcar-lesson1:23:16: error: 'dir2PinR' was not declared in this scope

   digitalWrite(dir2PinR,LOW);

                ^

C:UsersWilliamDocumentssmartcar-lesson1smartcar-lesson1.ino: In function 'void go_Left()':

smartcar-lesson1:27:16: error: 'dir1PinL' was not declared in this scope

   digitalWrite(dir1PinL, HIGH);

                ^

smartcar-lesson1:28:16: error: 'dir2PinL' was not declared in this scope

   digitalWrite(dir2PinL,LOW);

                ^

smartcar-lesson1:29:16: error: 'dir1PinR' was not declared in this scope

   digitalWrite(dir1PinR,LOW);

                ^

smartcar-lesson1:30:16: error: 'dir2PinR' was not declared in this scope

   digitalWrite(dir2PinR,HIGH);

                ^

C:UsersWilliamDocumentssmartcar-lesson1smartcar-lesson1.ino: In function 'void go_Right()':

smartcar-lesson1:34:16: error: 'dir1PinL' was not declared in this scope

   digitalWrite(dir1PinL, LOW);

                ^

smartcar-lesson1:35:16: error: 'dir2PinL' was not declared in this scope

   digitalWrite(dir2PinL,HIGH);

                ^

smartcar-lesson1:36:16: error: 'dir1PinR' was not declared in this scope

   digitalWrite(dir1PinR,HIGH);

                ^

smartcar-lesson1:37:16: error: 'dir2PinR' was not declared in this scope

   digitalWrite(dir2PinR,LOW);

                ^

C:UsersWilliamDocumentssmartcar-lesson1smartcar-lesson1.ino: In function 'void go_Back()':

smartcar-lesson1:41:16: error: 'dir1PinL' was not declared in this scope

   digitalWrite(dir1PinL, LOW);

                ^

smartcar-lesson1:42:16: error: 'dir2PinL' was not declared in this scope

   digitalWrite(dir2PinL,HIGH);

                ^

smartcar-lesson1:43:16: error: 'dir1PinR' was not declared in this scope

   digitalWrite(dir1PinR,LOW);

                ^

smartcar-lesson1:44:16: error: 'dir2PinR' was not declared in this scope

   digitalWrite(dir2PinR,HIGH);

                ^

C:UsersWilliamDocumentssmartcar-lesson1smartcar-lesson1.ino: In function 'void stop_Stop()':

smartcar-lesson1:48:16: error: 'dir1PinL' was not declared in this scope

   digitalWrite(dir1PinL, LOW);

                ^

smartcar-lesson1:49:16: error: 'dir2PinL' was not declared in this scope

   digitalWrite(dir2PinL,LOW);

                ^

smartcar-lesson1:50:16: error: 'dir1PinR' was not declared in this scope

   digitalWrite(dir1PinR,LOW);

                ^

smartcar-lesson1:51:16: error: 'dir2PinR' was not declared in this scope

   digitalWrite(dir2PinR,LOW);

                ^

C:UsersWilliamDocumentssmartcar-lesson1smartcar-lesson1.ino: In function 'void set_Motorspeed(int, int)':

smartcar-lesson1:57:15: error: 'speedPinL' was not declared in this scope

   analogWrite(speedPinL,speed_L); 

               ^

smartcar-lesson1:58:15: error: 'speedPinR' was not declared in this scope

   analogWrite(speedPinR,speed_R);   

               ^

C:UsersWilliamDocumentssmartcar-lesson1smartcar-lesson1.ino: In function 'void init_GPIO()':

smartcar-lesson1:64:10: error: 'dir1PinL' was not declared in this scope

  pinMode(dir1PinL, OUTPUT); 

          ^

smartcar-lesson1:65:10: error: 'dir2PinL' was not declared in this scope

  pinMode(dir2PinL, OUTPUT); 

          ^

smartcar-lesson1:66:10: error: 'speedPinL' was not declared in this scope

  pinMode(speedPinL, OUTPUT);  

          ^

smartcar-lesson1:68:10: error: 'dir1PinR' was not declared in this scope

  pinMode(dir1PinR, OUTPUT);

          ^

smartcar-lesson1:69:11: error: 'dir2PinR' was not declared in this scope

   pinMode(dir2PinR, OUTPUT); 

           ^

smartcar-lesson1:70:11: error: 'speedPinR' was not declared in this scope

   pinMode(speedPinR, OUTPUT); 

           ^

exit status 1
'dir1PinL' was not declared in this scope

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Arduino: 1.8.10 (Windows 10), Плата:»WeMos D1 R1, 80 MHz, Flash, Disabled, All SSL ciphers (most compatible), 4M (1M SPIFFS), v2 Higher Bandwidth, Disabled, None, Only Sketch, 921600″

In file included from C:UsersUserDesktopGyverLamp-masterGyverLamp-masterfirmwareGyverLamp_v1.4_MQTTGyverLamp_v1.4_MQTT.ino:88:0:

C:UsersUserDocumentsArduinolibrariesFastLED-master/FastLED.h:17:21: note: #pragma message: FastLED version 3.001.005

# pragma message «FastLED version 3.001.005»

^

In file included from C:UsersUserDocumentsArduinolibrariesFastLED-master/led_sysdefs.h:27:0,

from C:UsersUserDocumentsArduinolibrariesFastLED-master/FastLED.h:44,

from C:UsersUserDesktopGyverLamp-masterGyverLamp-masterfirmwareGyverLamp_v1.4_MQTTGyverLamp_v1.4_MQTT.ino:88:

C:UsersUserDocumentsArduinolibrariesFastLED-master/platforms/esp/8266/led_sysdefs_esp8266.h:15:17: error: conflicting declaration ‘typedef uint8_t boolean’

typedef uint8_t boolean;

^

In file included from sketchGyverLamp_v1.4_MQTT.ino.cpp:1:0:

C:UsersUserAppDataLocalArduino15packagesesp8266hardwareesp82662.5.2coresesp8266/Arduino.h:191:14: error: ‘boolean’ has a previous declaration as ‘typedef bool boolean’

typedef bool boolean;

^

In file included from C:UsersUserDocumentsArduinolibrariesFastLED-master/FastLED.h:65:0,

from C:UsersUserDesktopGyverLamp-masterGyverLamp-masterfirmwareGyverLamp_v1.4_MQTTGyverLamp_v1.4_MQTT.ino:88:

C:UsersUserDocumentsArduinolibrariesFastLED-master/fastspi.h:110:23: note: #pragma message: No hardware SPI pins defined. All SPI access will default to bitbanged output

# pragma message «No hardware SPI pins defined. All SPI access will default to bitbanged output»

^

C:UsersUserDesktopGyverLamp-masterGyverLamp-masterfirmwareGyverLamp_v1.4_MQTTGyverLamp_v1.4_MQTT.ino: In function ‘void setup()’:

GyverLamp_v1.4_MQTT:204:9: error: ‘class GButton’ has no member named ‘setClickTimeout’

touch.setClickTimeout(500);

^

Несколько библиотек найдено для «DNSServer.h»
Используется: C:UsersUserAppDataLocalArduino15packagesesp8266hardwareesp82662.5.2librariesDNSServer
Несколько библиотек найдено для «GyverButton.h»
Используется: C:UsersUserDocumentsArduinolibrariesGyverButton
Не используется: C:arduino-1.8.10-windowsarduino-1.8.10librariesGyverButton
Несколько библиотек найдено для «ESP8266WiFi.h»
Используется: C:UsersUserAppDataLocalArduino15packagesesp8266hardwareesp82662.5.2librariesESP8266WiFi
Несколько библиотек найдено для «EEPROM.h»
Используется: C:UsersUserAppDataLocalArduino15packagesesp8266hardwareesp82662.5.2librariesEEPROM
Несколько библиотек найдено для «Timer.h»
Используется: C:arduino-1.8.10-windowsarduino-1.8.10librariesTimer
Несколько библиотек найдено для «ESP8266WebServer.h»
Используется: C:UsersUserAppDataLocalArduino15packagesesp8266hardwareesp82662.5.2librariesESP8266WebServer
Несколько библиотек найдено для «ESP8266HTTPUpdateServer.h»
Используется: C:UsersUserAppDataLocalArduino15packagesesp8266hardwareesp82662.5.2librariesESP8266HTTPUpdateServer
Несколько библиотек найдено для «PubSubClient.h»
Используется: C:arduino-1.8.10-windowsarduino-1.8.10librariesPubSubClient
Несколько библиотек найдено для «ArduinoJson.h»
Используется: C:arduino-1.8.10-windowsarduino-1.8.10librariesArduinoJson
Несколько библиотек найдено для «FastLED.h»
Используется: C:UsersUserDocumentsArduinolibrariesFastLED-master
Не используется: C:arduino-1.8.10-windowsarduino-1.8.10librariesFastLED-3.2.9
Несколько библиотек найдено для «ESP8266mDNS.h»
Используется: C:UsersUserAppDataLocalArduino15packagesesp8266hardwareesp82662.5.2librariesESP8266mDNS
Несколько библиотек найдено для «WiFiManager.h»
Используется: C:arduino-1.8.10-windowsarduino-1.8.10librariesWiFiManager
Несколько библиотек найдено для «NTPClient.h»
Используется: C:arduino-1.8.10-windowsarduino-1.8.10librariesNTPClient-master
Несколько библиотек найдено для «ArduinoOTA.h»
Используется: C:UsersUserAppDataLocalArduino15packagesesp8266hardwareesp82662.5.2librariesArduinoOTA
exit status 1
‘class GButton’ has no member named ‘setClickTimeout’

Этот отчёт будет иметь больше информации с
включенной опцией Файл -> Настройки ->
«Показать подробный вывод во время компиляции»

Понравилась статья? Поделить с друзьями:
  • Error list labview
  • Error list is null
  • Error list is not a template
  • Error linux route delete command failed could not execute external program
  • Error linking with uncompiled unspecialized shader