Error exit was not declared in this scope

Программа, которая выдает размер директории. Выдает ошибку в строчке exit (1). " 'exit' was not declared in this scope". В чем может быть ошибка? #include #include #

Насчёт гугла я не стал бы рекомендовать. За то, что там выдаст гугл — не отвечает никто. Но есть официальный источник информации — man система.

По первому вопросу. Смотрим man 3 exit. Там в третьей строке написано:

#include <stdlib.h>

И не надо ни у какого гугла спрашивать — там, зачастую,содержатся совершенно противоречивые советы. Подсказка: в команде man второй парамерт означает:

  1. Команда Shell
  2. Системный вызов (обращение к ядру ОС)
  3. Вызов функции из стандартной библиотеки.

По второму вопросу: «что вернёт stat() на каталог?». С точки зрения ФС наиболее распространённых типов (EXT3, EXT4), каталог — это самый обычный файл, в котором содержатся записи определённой структуры. Что бы понять, как отличить регулярный файл от каталога, опять таки смотрим man 2 stat. Там даже пример приведён:

stat(pathname, &sb);
if ((sb.st_mode & S_IFMT) == S_IFREG) {
     /* Handle regular file */
}

Ну и третий вопрос — про ‘.’ и ‘..’. С точки зрения ФС это просто обозначения (синонимы) для реальных каталогов — текущего и родительского. Поэтому их обработка ничем не отличается от обработки каталогов, заданных явно.

Forum

  • Beginners
  • Windows Programming
  • UNIX/Linux Programming
  • General C++ Programming
  • Lounge
  • Jobs
  • Forum
  • General C++ Programming
  • Stacks: [Error] ‘exit’ was not declared

Stacks: [Error] ‘exit’ was not declared in this scope.

So our professor asked us to make a project where we will need three files (two .cpp files and one .h file) This is regarding our topic about Stacks. When I compile the project in Dev C++, I only get one error which is the [Error] ‘exit’ was not declared in this scope. Can anyone please tell me how to solve this? I’m really close letting this program run. Only the exit isn’t working. Would appreciate your help. Thank you!

Here’s the code for Stacks.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 
#ifndef STACK 
#define STACK

const int STACK_CAPACITY = 128;
typedef int StackElement;

class Stack 
{
	public: 
	Stack(); 
	bool empty() const; 
	void push(const StackElement &value);
	void display(ostream &out) const; 
	StackElement top() const; 
	void pop();
	
	private: 
	StackElement myArray[STACK_CAPACITY]; 
	int myTop;

};

#endif 

Here’s the code for Stacks.cpp

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
#include <iostream> 
using namespace std;

#include "Stack.h"

Stack::Stack(){
	myTop--; 
}

bool Stack::empty() const 
{
	return (myTop == -1);
}

void Stack::push(const StackElement &value) 
{
		if (myTop < STACK_CAPACITY - 1)	
		{
			++myTop;
			myArray[myTop] - value;
		}
		else
		{
			cerr << "*** Stack full -- can't add new value ***n"
				    "Must increase value of STACK_CAPACITY in Stack.hn";
			exit(1);
		}
}

void Stack::display(ostream &out) const 
{
	for (int i = myTop; i >= 0; i--) 
		cout << myArray[i] << endl;
}

StackElement Stack::top() const 
{
	if ( !empty() )
		return (myArray[myTop]); 
	else
	{
		cerr << "*** Stack is empty -- returning garbage value ***n"; 
		StackElement garbage; return garbage;

	}
}

void Stack::pop() 
{
	if ( !empty() )
		myTop--; 
	else
		cerr << "*** Stack is empty -- can't remove a value ***n";		
}

Here’s the code for Driver.cpp

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
#include <iostream> 
using namespace std;

#include "Stack.h"

int main()
{
	Stack s; 
	cout « "Stack created. Empty?"« boolalpha « s.empty() « endl;
	
	cout « "How many elements to add to the stack? "; 
	int numItems; 
	cin » numItems;
	for (int i = 1; <=numItems; i++) 
		s.push(i);
	
	cout « "Stack contents:n"; 
	s.display(cout);
	
	cout « "Stack empty? " « s.empty() « endl;
	
	cout « "Top value: " « s.top() « endl;

	while (!s.empty()) 
	{
		cout « "Popping " « s.top() « endl; 
		s.pop();
	}

	cout « "Stack empty? " « s.empty() « endl; 
	cout « "Top value: " « s.top() « endl; 
	cout « "Trying to pop:" « endl; 
	s.pop();
}

exit() is declared in the header <cstdlib> (or <stdlib.h> for C programs). You just need #include <cstdlib> in Stacks.cpp.

Also, If you use Dev-C++, please make sure it is the Orwell version. Earlier versions are considered obsolete. http://orwelldevcpp.blogspot.com/

Topic archived. No new replies allowed.

  • #1

Использую arduino 1.8.6.

При проверки выдаёт ошибку

Gamepad_ProjectKPP:31:3: error: 'Gamepad' was not declared in this scope
exit status 1
'Gamepad' was not declared in this scope

Сам код.

const int pinButton2 = 2;

const int pinButton4 = 4;


void setup() {

  pinMode(pinButton2, INPUT_PULLUP);

  pinMode(pinButton4, INPUT_PULLUP);


  Gamepad.begin();

}


void loop() {


   if (!digitalRead(pinButton2))

   Gamepad.press(2);

  else

    Gamepad.release(2);

 

  if (!digitalRead(pinButton4))

    Gamepad.press(4);

  else

    Gamepad.release(4);


  Gamepad.write();

}

  • #2

Использую arduino 1.8.6.

При проверки выдаёт ошибку

Gamepad_ProjectKPP:31:3: error: 'Gamepad' was not declared in this scope
exit status 1
'Gamepad' was not declared in this scope

Сам код.

const int pinButton2 = 2;

const int pinButton4 = 4;


void setup() {

  pinMode(pinButton2, INPUT_PULLUP);

  pinMode(pinButton4, INPUT_PULLUP);


  Gamepad.begin();

}


void loop() {


   if (!digitalRead(pinButton2))

   Gamepad.press(2);

  else

    Gamepad.release(2);



  if (!digitalRead(pinButton4))

    Gamepad.press(4);

  else

    Gamepad.release(4);


  Gamepad.write();

}

если это весь код, то не хватает библиотеки описывающей класс Gamepad , если нет то кидайте весь скетч…

  • #3

если это весь код, то не хватает библиотеки описывающей класс Gamepad , если нет то кидайте весь скетч…

Это весь код. Я искал библиотеку Gamepad, не нашел.
Можно этот код переписать, чтобы он работал без этой библиотеки?

  • #5

Помогло но сейчас появилась новая ошибка.

Не используется: E:DocumentsArduinolibrariesHID-2.5.0
E:DocumentsArduinolibrariesHID-Projectsrc/HID-Project.h:35:2: error: #error HID Project can only be used with an USB MCU.

 #error HID Project can only be used with an USB MCU.

  ^

exit status 1
Ошибка компиляции для платы Arduino Pro or Pro Mini.
Выбранная папка/zip файл не содержит корректных библиотек

Your_Andrew


  • #6

Нужно библиотеку GamePad перенести в папку где храняться все библиотеки Ардуино.

  • #7

Arduino UNO тебе поможет,
нельзя просто брать и копировать чей-то проект смотри для каких плат его проектировали…

  • #8

Arduino UNO тебе поможет,
нельзя просто брать и копировать чей-то проект смотри для каких плат его проектировали…

Этот код для рычага кпп для кнопок. Ясно, все спасибо за помощь.

Изменено: 27 Янв 2019

  • #9

Arduino UNO тебе поможет,
нельзя просто брать и копировать чей-то проект смотри для каких плат его проектировали…

МОЖНО и НУЖНО, иначе зачем всё это?

AlexGyver


  • #10

@Gogsia, библиотека работает только с Leonardo/Micro/Pro Micro

  • #11

Здравствуйте.
Столкнулся с такой же проблемой «error HID Project can only be used with an USB MCU». Получается между платами есть какая-то разница в реализации USB? Ткните носом пожалуйста, где про это можно прочитать подробнее? Хочется понять на будущее возможные проблемы у USB при выборе плат для проектов.
Спасибо.

  • #12

Короче разница в том, что у одних плат контроллер это отдельный чип и он убогий, у других же поддержка USB нативная в самом контроллере.

лови:

/*
Лабораторный блок питания под управлением arduino
Версия 2 (26.02.2015)
Для дополнительной информации посетите http://start.net.ua/blog/lab_power_arduino/
*/

#include <LiquidCrystal.h>;
#include <EEPROM.h>
LiquidCrystal lcd(11, 6, 5, 4, 3, 2); //rs, e, d4, d5, d6, d7

// задаем константы

float umax = 17.00; //максимальное напряжение
float umin = 0.00; //минимальное напряжение
float ah = 0.0000; //Cчетчик Ампер*часов
const int down = 10; //выход валкодера 1/2
const int up = 8; //выход валкодера 2/2
const int pwm = 9; //выход ШИМ
const int power = 7; //управление релюхой
long previousMillis = 0; //храним время последнего обновления дисплея
long maxpwm = 0; //циклы поддержки максимального ШИМ
long interval = 500; // интервал обновления информации на дисплее, мс
int mig = 0; //Для енкодера (0 стоим 1 плюс 2 минус)
float level = 0; //»уровень» ШИМ сигнала
float com = 100;
long com2 = 0;
int mode = 0;//режим (0 обычный, спабилизация тока, защита по току)
int mode1 = 0;
float Ioutmax = 1.0; //заданный ток
int set = 0; //пункты меню, отображение защиты…
int knopka_a = 0; //состояние кнопок
int knopka_b = 0;
int knopka_ab = 0;
boolean off = false;
boolean red = false;
boolean blue = false;
float counter = 5; // переменная хранит заданное напряжение
int disp = 0; //режим отображения 0 ничего, 1 мощьность, 2 режим, 3 установленный ток, 4 шим уровень
float Uout ; //напряжение на выходе

const int Pin=A2; // номер выхода, подключенного к реле
int PinState = LOW; // этой переменной устанавливаем состояние реле
long previousMillis1 = 0; // храним время последнего переключения реле
long interval1 = 1000; // интервал между включение/выключением реле (1 секунда)
long interval2 = 500;

int incomingByte;

void EEPROM_float_write(int addr, float val) // запись в ЕЕПРОМ
{
byte *x = (byte *)&val;
for(byte i = 0; i < 4; i++) EEPROM.write(i+addr, x[i]);
}

float EEPROM_float_read(int addr) // чтение из ЕЕПРОМ
{
byte x[4];
for(byte i = 0; i < 4; i++) x[i] = EEPROM.read(i+addr);
float *y = (float *)&x;
return y[0];
}

void setup() {
cli();
DDRB |= 1<<1 | 1<<2;
PORTB &= ~(1<<1 | 1<<2);
TCCR1A = 0b00000010;
//TCCR1A = 0b10100010;
TCCR1B = 0b00011001;
ICR1H = 255;
ICR1L = 255;
sei();
int pwm_rez = 13;
pwm_rez = pow(2, pwm_rez);
ICR1H = highByte(pwm_rez);
ICR1L = lowByte(pwm_rez);

// задаем режим выхода для порта, подключенного к реле
pinMode(Pin, OUTPUT);

Serial.begin(9600);

pinMode(pwm, OUTPUT);
pinMode(down, INPUT);
pinMode(up, INPUT);
pinMode(12, INPUT);
pinMode(13, INPUT);
pinMode(power, OUTPUT);
pinMode(A4, OUTPUT);
pinMode(A5, OUTPUT);
// поддерживаем еденицу на входах от валкодера
digitalWrite(up, 1);
digitalWrite(down, 1);
//поддерживаем еденицу на контактах кнопок
digitalWrite(12, 1);
digitalWrite(13, 1);
//запуск дисплея
lcd.begin(16, 2);
lcd.print(» WELCOME! «);

//загружаем настройки из памяти МК
counter = EEPROM_float_read(0);
Ioutmax = EEPROM_float_read(4);
mode = EEPROM_float_read(12);
disp = EEPROM_float_read(10);
//Если в памяти еще нет настроек — задаем что нибудь кроме нулей
if(counter==0) counter = 5; //5 вольт
if(Ioutmax==0) Ioutmax = 2; //2 ампера

//включаем реле
digitalWrite(power, 1);
}

//функции при вращении енкодера
void uup(){ //енкодер +
if(set==0){//обычный режим — добавляем напряжения
if(counter<umax) {
counter = counter+0.1;//добавляем
}
}
if(set==1){ //переключаем режим работы вперед
mode = mode+1;
if(mode>2) mode=2;
}

if(set==2){ //переключаем режим работы вперед (ON)
mode1 = mode1+1;
if(mode1>1) mode1=1;
}
if(set==3){ //настройка тока, добавляем ток
iplus();
}

if(set==4){//сброс счетчика А*ч
ah = 0;
set = 0;
disp = 5;
}

if(set==5){//сохранение текущих настроек в память
save();
}
}

void udn(){ //валкодер —
if(set==0){
if(counter>umin+0.1)counter = counter-0.1; //убавляем напнряжение
}
if(set==1){
mode = mode-1; //переключаем режим работы назад
if(mode<0) mode=0;
}
if(set==2){ //переключаем режим работы назад (OFF)
mode1 = mode1-1;
if(mode1<0) mode1=0;
}
if(set==3){//убавляем ток
iminus();
}
}

void iplus(){
Ioutmax = Ioutmax+0.01;
if(Ioutmax>0.2) Ioutmax=Ioutmax+0.04;
if(Ioutmax>1) Ioutmax=Ioutmax+0.05;

if(Ioutmax>8.00) Ioutmax=8.00;
}

void iminus(){
Ioutmax = Ioutmax-0.01;
if(Ioutmax>0.2) Ioutmax=Ioutmax-0.04;
if(Ioutmax>1) Ioutmax=Ioutmax-0.05;

if(Ioutmax<0.03) Ioutmax=0.03;
}

void save(){
lcd.clear();
lcd.setCursor (0, 0);
lcd.print(» S A V E — OK «);

EEPROM_float_write(0, counter);
EEPROM_float_write(4, Ioutmax);
EEPROM_float_write(12, mode);
EEPROM_float_write(10, disp);
//мигаем светодиодами
digitalWrite(A4, 1);
digitalWrite(A5, 1);
delay(500);
digitalWrite(A4, 0);
digitalWrite(A5, 0);
set = 0; //выходим из меню
}

void loop() //основной цикл работы МК
{

// здесь будет код, который будет работать постоянно
// и который не должен останавливаться на время между переключениями свето
unsigned long currentMillis1 = millis();

//проверяем не прошел ли нужный интервал, если прошел то
if((currentMillis1 — previousMillis1 > interval1)&(mode1==1)) {
// сохраняем время последнего переключения
previousMillis1 = currentMillis1;

// если светодиод не горит, то зажигаем, и наоборот

if (PinState == LOW)
PinState = HIGH;

else
PinState = LOW;

// устанавливаем состояния выхода, чтобы включить или выключить светодиод
digitalWrite(Pin, PinState);
}

unsigned long currentMillis = millis();

/* Вншнее управление */
if (Serial.available() > 0) { //если есть доступные данные
// считываем байт
incomingByte = Serial.read();

}else{
incomingByte = 0;
}

if(incomingByte==97){ //a
if(counter>umin+0.1)counter = counter-0.1; //убавляем напнряжение

}
if(incomingByte==98){ //b

if(counter<umax) counter = counter+0.1;//добавляем

}

if(incomingByte==99){ //c
iminus();
}

if(incomingByte==100){ //d
iplus();
}

if(incomingByte==101) mode = 0;
if(incomingByte==102) mode = 1;
if(incomingByte==103) mode = 2;
if(incomingByte==104) mode1 = 1;
if(incomingByte==105) save();
if(incomingByte==106){
digitalWrite(power, 1); //врубаем реле если оно было выключено
delay(100);
digitalWrite(A4, 0); //гасим красный светодиод
Serial.print(‘t’);
Serial.print(0);
Serial.print(‘;’);
off = false;
set = 0;//выходим из меню
}

if(incomingByte==107) off = true;
if(incomingByte==108) ah = 0;

/* конец внешнего управления */

//получаем значение напряжения и тока в нагрузке
//float Ucorr = 0.00; //коррекция напряжения, при желании можно подстроить
//float Uout = analogRead(A1) * ((5.0 + Ucorr) / 1023.0) * 5.0; //узнаем напряжение на выходе
float Uout = analogRead(A1) * (5.0 / 1023.0) * 5.0; //узнаем напряжение на выходе

float Iout = analogRead(A0) / 100.00; // узнаем ток в нагрузке

//if(Iout==0.01) Iout = 0.03; else
//if(Iout==0.02) Iout = 0.04; else
//if(Iout==0.03) Iout = 0.05; else
//if(Iout==0.04) Iout = 0.06; else
//if(Iout>=0.05) Iout = Iout + 0.02;
//if(Iout>=0.25)Iout = Iout + 0.01;
//if(Iout>=1)Iout = Iout * 1.02;

/* ЗАЩИТА и выключение */

if (((Iout>(counter+0.3)*2.0) | Iout>10.0 | off) & set<4 & millis()>100 ) // условия защиты

{
digitalWrite(power, 0); //вырубаем реле
level = 0; //убираем ШИМ сигнал
digitalWrite(A4, 1);

Serial.print(‘I0;U0;r1;W0;’);
Serial.println(‘ ‘);
set = 6;

}

//Зашита от длительного максимального шим
if (level==8190 & off==false)
{
if(set<4)//если уже не сработала защита
{
maxpwm++; //добавляем +1 к счетчику
digitalWrite(A4, 1); //светим красным для предупреждения о максимальном ШИМ
}
}
else //шим у нас не максимальный, поэтому поубавим счетчик
{
maxpwm—;
if(maxpwm<0)//если счетчик дошел до нуля
{
maxpwm = 0; //таким его и держим
if(set<4) digitalWrite(A4, 0); // гасим красный светодиод. Перегрузки нет.
}
}

/* ЗАЩИТА КОНЕЦ */

// считываем значения с входа валкодера
boolean regup = digitalRead(up);
boolean regdown = digitalRead(down);

if(regup<regdown) mig = 1; // крутится в сторону увеличения
if(regup>regdown) mig = 2; // крутится в сторону уменшения
if(!regup & !regdown) //момент для переключения
{
if(mig==1) uup();//+
if(mig==2) udn(); //-
mig = 0; //сбрасываем указатель направления
}

if(mode==0 | mode==1) //если управляем только напряжением (не режим стабилизации тока)
{

//Сравниваем напряжение на выходе с установленным, и принимаем меры..
if(Uout>counter)
{
float raz = Uout — counter; //на сколько напряжение на выходе больше установленного…
if(raz>0.05)
{
level = level — raz * 20; //разница большая управляем грубо и быстро!
}else{
if(raz>0.015) level = level — raz * 3 ; //разница небольшая управляем точно
}
}
if(Uout<counter)
{
float raz = counter — Uout; //на сколько напряжение меньше чем мы хотим
if(raz>0.05)
{
level = level + raz * 20; //грубо
}else{
if(raz>0.015) level = level + raz * 3 ; //точно
}
}

if(mode==1&&Iout>Ioutmax) //режим защиты по току, и он больше чем мы установили
{
digitalWrite(power, 0); //вырубаем реле
Serial.print(‘t’);
Serial.print(2);
Serial.print(‘;’);

//зажигаем красный светодиод
digitalWrite(A4, 1);
level = 0; //убираем ШИМ сигнал
set=5; //режим ухода в защиту…
}

}else{ //режим стабилизации тока

if(Iout>=Ioutmax)
{
//узнаем запас разницу между током в нагрузке и установленным током
float raz = (Iout — Ioutmax);
if(raz>0.3) //очень сильно превышено (ток больше заданного более чем на 0,3А)
{
level = level — raz * 20; //резко понижаем ШИМ
}else{
if(raz>0.05) //сильно превышено (ток больше заданного более чем на 0,1А)
{
level = level — raz * 5; //понижаем ШИМ
}else{
if(raz>0.00) level = level — raz * 2; //немного превышен (0.1 — 0.01А) понижаем плавно
}
}

//зажигаем синий светодиод
digitalWrite(A5, 1);
}else{ //режим стабилизации тока, но ток у нас в пределах нормы, а значит занимаемся регулировкой напряжения
digitalWrite(A5, 0);//синий светодиод не светится

//Сравниваем напряжение на выходе с установленным, и принимаем меры..
if(Uout>counter)
{
float raz = Uout — counter; //на сколько напряжение на выходе больше установленного…
if(raz>0.1)
{
level = level — raz * 20; //разница большая управляем грубо и быстро!
}else{
if(raz>0.015) level = level — raz * 5; //разница небольшая управляем точно
}
}
if(Uout<counter)
{
float raz = counter — Uout; //на сколько напряжение меньше чем мы хотим
float iraz = (Ioutmax — Iout); //
if(raz>0.1 & iraz>0.1)
{
level = level + raz * 20; //грубо
}else{
if(raz>0.015) level = level + raz ; //точно
}
}
}
}//конец режима стабилизации тока

if(off) level = 0;
if(level<0) level = 0; //не опускаем ШИМ ниже нуля
if(level>8190) level = 8190; //не поднимаем ШИМ выше 13 бит
//Все проверили, прощитали и собственно отдаем команду для силового транзистора.
if(ceil(level)!=255) analogWrite(pwm, ceil(level)); //подаем нужный сигнал на ШИМ выход (кроме 255, так как там какая-то лажа)

/* УПРАВЛЕНИЕ */

if (digitalRead(13)==0 && digitalRead(12)==0 && knopka_ab==0 ) { // нажата ли кнопка a и б вместе
knopka_ab = 1;

//ah = 0.000;

knopka_ab = 0;
}

if (digitalRead(13)==0 && knopka_a==0) { // нажата ли кнопка А (disp)
knopka_a = 1;
disp = disp + 1; //поочередно переключаем режим отображения информации
if(disp==6) disp = 0; //дошли до конца, начинаем снова
}

if (digitalRead(12)==0 && knopka_b==0) { // нажата ли кнопка Б (menu)
knopka_b = 1;
set = set+1; //
if(set>5 | off) {//Задействован один из режимов защиты, а этой кнопкой мы его вырубаем. (или мы просто дошли до конца меню) //количество меню
off = false;
digitalWrite(power, 1); //врубаем реле если оно было выключено
delay(100);
digitalWrite(A4, 0); //гасим красный светодиод
Serial.print(‘t’);
Serial.print(0);
Serial.print(‘;’);
Serial.print(‘r’);
Serial.print(0);
Serial.print(‘;’);
Serial.println(‘ ‘);
set = 0;//выходим из меню
}
lcd.clear();//чистим дисплей
}

//сбрасываем значения кнопок или чего-то вроде того.
if(digitalRead(12)==1&&knopka_b==1) knopka_b = 0;
if(digitalRead(13)==1&&knopka_a==1) knopka_a = 0;

/* COM PORT */

if(currentMillis — com2 > com) {
// сохраняем время последнего обновления
com2 = currentMillis;

//Считаем Ампер*часы
ah = ah + (Iout / 36000);

Serial.print(‘U’);
Serial.print(Uout);
Serial.print(‘;’);

Serial.print(‘I’);
Serial.print(Iout);
Serial.print(‘;’);

Serial.print(‘i’);
Serial.print(Ioutmax);
Serial.print(‘;’);

Serial.print(‘u’);
Serial.print(counter);
Serial.print(‘;’);

Serial.print(‘W’);
Serial.print(level);
Serial.print(‘;’);

Serial.print(‘c’);
Serial.print(ah);
Serial.print(‘;’);

Serial.print(‘m’);
Serial.print(mode);
Serial.print(‘;’);

Serial.print(‘r’);
Serial.print(digitalRead(A4));
Serial.print(‘;’);

Serial.print(‘b’);
Serial.print(digitalRead(A5));
Serial.print(‘;’);

Serial.println(‘ ‘);

}

/* ИНДИКАЦИЯ LCD */

if(set==0){
//стандартный екран

//выводим уснановленное напряжение на дисплей
lcd.setCursor (0, 1);
lcd.print(«U>»);
if(counter<10) lcd.print(» «); //добавляем пробел, если нужно, чтобы не портить картинку
lcd.print (counter,1); //выводим установленное значение напряжения
lcd.print («V «); //пишем что это вольты

//обновление информации

/*проверяем не прошел ли нужный интервал, если прошел то
выводим реальные значения на дисплей*/

if(currentMillis — previousMillis > interval) {
// сохраняем время последнего обновления
previousMillis = currentMillis;
//выводим актуальные значения напряжения и тока на дисплей

lcd.setCursor (0, 0);
lcd.print(«U=»);
if(Uout<9.99) lcd.print(» «);
lcd.print(Uout,2);
lcd.print(«V I=»);
lcd.print(Iout, 2);
lcd.print(«A «);

//дополнительная информация
lcd.setCursor (8, 1);
if(disp==0){ //ничего
lcd.print(» «);
}
if(disp==1){ //мощьность
lcd.print(» «);
lcd.print (Uout * Iout,2);
lcd.print(«W «);
}
if(disp==2){ //режим БП
if(mode==0)lcd.print («standart»);
if(mode==1)lcd.print («shutdown»);
if(mode==2)lcd.print (» drop»);
}
if(disp==3){ //режим БП
if(mode1==0) lcd.print(«Off»);
if(mode1==1) lcd.print(«On «);
}
if(disp==4){ //максимальный ток
lcd.print (» I>»);
lcd.print (Ioutmax, 2);
lcd.print («A «);
}
if(disp==5){ // значение ШИМ
lcd.print («pwm:»);
lcd.print (ceil(level), 0);
lcd.print (» «);
}
if(disp==6){ // значение ШИМ
if(ah<1){
//if(ah<0.001) lcd.print (» «);
if(ah<=0.01) lcd.print (» «);
if(ah<=0.1) lcd.print (» «);
lcd.print (ah*1000, 1);
lcd.print («mAh «);
}else{
if(ah<=10) lcd.print (» «);
lcd.print (ah, 3);
lcd.print («Ah «);
}
}
}
}

/* ИНДИКАЦИЯ МЕНЮ */
if(set==1)//выбор режима
{
lcd.setCursor (0, 0);
lcd.print(«> MENU 1/5 «);
lcd.setCursor (0, 1);
lcd.print(«mode: «);
//режим (0 обычный, спабилизация тока, защита по току)
if(mode==0) lcd.print(«normal «);
if(mode==1) lcd.print(«shutdown «);
if(mode==2) lcd.print(«drop «);
}

if(set==2){//настройка сульфатации
lcd.setCursor (0, 0);
lcd.print(«> MENU 2/5 «);
lcd.setCursor (0, 1);
lcd.print(«DeSulfat: «);
if(mode1==0) lcd.print(«Off»);
if(mode1==1) lcd.print(«On «);

}
if(set==3){//настройка тока
lcd.setCursor (0, 0);
lcd.print(«> MENU 3/5 «);
lcd.setCursor (0, 1);
lcd.print(«I out max: «);
lcd.print(Ioutmax);
lcd.print(«A»);
}
if(set==4){//спрашиваем хочет ли юзер сохранить настройки
lcd.setCursor (0, 0);
lcd.print(«> MENU 4/5 «);
lcd.setCursor (0, 1);
lcd.print(«Reset A*h? ->»);
}

if(set==5){//спрашиваем хочет ли юзер сохранить настройки
lcd.setCursor (0, 0);
lcd.print(«> MENU 5/5 «);
lcd.setCursor (0, 1);
lcd.print(«Save options? ->»);
}
/* ИНДИКАЦИЯ ЗАЩИТЫ */
if(set==6){//защита. вывод инфы
lcd.setCursor (0, 0);
lcd.print(«ShutDown! «);
lcd.setCursor (0, 1);
lcd.print(«Iout»);
lcd.print(«>Imax(«);
lcd.print(Ioutmax);
lcd.print(«A)»);
level=0;
Serial.print(‘I0;U0;r1;W0;’);
Serial.println(‘ ‘);
}

if(set==7){//защита. вывод инфы критическое падение напряжения
Serial.print(‘I0;U0;r1;W0;’);
digitalWrite(A4, true);
Serial.println(‘ ‘);
level=0;
lcd.setCursor (0, 0);
if (off==false){ lcd.print(«[ OVERLOAD ]»);
lcd.setCursor (0, 1);
//и обьясняем юзеру что случилось

if((Iout>(counter+0.3)*2.0) | Iout>10.0){
Serial.print(‘t’);
Serial.print(1);
Serial.print(‘;’);
lcd.print(» Iout >= Imax «);
}

}else{

lcd.print(«[ OFF ]»);
lcd.setCursor (0, 1);
Serial.print(‘t’);
Serial.print(4);
Serial.print(‘;’);
}
}

}

  1. Ошибка выглядит так:
    Arduino: 1.8.2 (Windows 8.1), Плата:»Arduino/Genuino Uno»

    C:UsersUserDocumentsArduinozvukzvuk.ino: In function ‘void loop()’:

    zvuk:42: error: ‘lcd’ was not declared in this scope

    lcd.backlight();

    ^

    exit status 1
    ‘lcd’ was not declared in this scope

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

    скетч:
    #include <Wire.h>

    boolean lcdon; // состояние лампы: true — включено, false — выключено
    #include <LiquidCrystal_I2C.h> // подключаем библиотеку ЖКИ
    #define printByte(args) write(args); //
    int Value=0;
    float Value_volt=0;

    void setup() // процедура setup

    {

    pinMode(12,OUTPUT); // пин 12 со светодиодом будет выходом (англ. «output»)

    pinMode(A0,INPUT); // к аналоговому входу A0 подключим датчик (англ. «intput»)

    lcdon=false; // начальное состояние — лампа выключена

    Serial.begin(9600); // подключаем монитор порта

    LiquidCrystal_I2C lcd(0x27,16,2); // Задаем адрес и размерность дисплея

    lcd.init(); // Инициализация lcd
    lcd.setCursor(0, 0); // Устанавливаем курсор в начало 1 строки

    }

    void loop() // процедура loop

    {
    Serial.println (analogRead(A0)); // выводим значение датчика на монитор
    if(analogRead(A0)>28) // регистрация хлопка на датчике звука

    {
    lcdon=!lcdon; // меняем статус лампы при регистрации хлопка
    Value = analogRead(A0);
    lcd.backlight();
    lcd.print (Value)

    delay(20); // задержка, «дребезга» хлопков

    }

    }

  2. вынеси обьявление lcd из setup() наружу

  3. переменные описанные в функции являются локальными и внутри другой функции не видны. lcd у тебя создаеца внутри функции setup(), соттвецтно loop() ничего про нее не знает.

  4. пацкаска
    int Value=0;
    float Value_volt=0;
    видны внутри обеих функций, а lcd — только унутре setup()

    дальше жувать?

  5. ничего не изменилось

    #include <Wire.h>

    boolean lcdon; // состояние лампы: true — включено, false — выключено
    #include <LiquidCrystal_I2C.h> // подключаем библиотеку ЖКИ
    #define printByte(args) write(args); //
    int Value=0;
    float Value_volt=0;

    void setup() // процедура setup

    {

    pinMode(12,OUTPUT); // пин 12 со светодиодом будет выходом (англ. «output»)

    pinMode(A0,INPUT); // к аналоговому входу A0 подключим датчик (англ. «intput»)

    lcdon=false; // начальное состояние — лампа выключена

    Serial.begin(9600); // подключаем монитор порта

    LiquidCrystal_I2C lcd(0x27,16,2); // Задаем адрес и размерность дисплея

    }

    void loop() // процедура loop

    {
    Serial.println (analogRead(A0)); // выводим значение датчика на монитор
    if(analogRead(A0)>28) // регистрация хлопка на датчике звука

    {
    lcdon=!lcdon; // меняем статус лампы при регистрации хлопка
    lcd.init(); // Инициализация lcd
    lcd.setCursor(0, 0); // Устанавливаем курсор в начало 1 строки

    Value = analogRead(A0);
    lcd.backlight();
    lcd.print (Value)

    delay(20); // задержка, «дребезга» хлопков

    }

    }

  6. ничего не поменял — ничего и не изменилось.
    и этта, код вставляй какследовает.

  7. перед setup вставлять lcd?

  8. Именно к этому я тебя и веду

#1 2013-08-28 22:17:44

MisterEwok
Member
Registered: 2013-08-28
Posts: 38

g++ isn’t compiling!

So, I noticed this yesterday, thinking it was application specific. Now I’ve tried compiling with multiple pieces of code that I’ve written, all of which compiled successfully at most a week ago. The following paste is from an attempt on a simple example (so as to minimize the amount to paste). I don’t know what I did to cause this. Any ideas?

g++  -c main.cpp
In file included from main.cpp:1:0:
/usr/include/c++/4.8.1/cstdlib:118:11: error: ‘::div_t’ has not been declared
   using ::div_t;
           ^
/usr/include/c++/4.8.1/cstdlib:119:11: error: ‘::ldiv_t’ has not been declared
   using ::ldiv_t;
           ^
/usr/include/c++/4.8.1/cstdlib:121:11: error: ‘::abort’ has not been declared
   using ::abort;
           ^
/usr/include/c++/4.8.1/cstdlib:122:11: error: ‘::abs’ has not been declared
   using ::abs;
           ^
/usr/include/c++/4.8.1/cstdlib:123:11: error: ‘::atexit’ has not been declared
   using ::atexit;
           ^
/usr/include/c++/4.8.1/cstdlib:129:11: error: ‘::atof’ has not been declared
   using ::atof;
           ^
/usr/include/c++/4.8.1/cstdlib:130:11: error: ‘::atoi’ has not been declared
   using ::atoi;
           ^
/usr/include/c++/4.8.1/cstdlib:131:11: error: ‘::atol’ has not been declared
   using ::atol;
           ^
/usr/include/c++/4.8.1/cstdlib:132:11: error: ‘::bsearch’ has not been declared
   using ::bsearch;
           ^
/usr/include/c++/4.8.1/cstdlib:133:11: error: ‘::calloc’ has not been declared
   using ::calloc;
           ^
/usr/include/c++/4.8.1/cstdlib:134:11: error: ‘::div’ has not been declared
   using ::div;
           ^
/usr/include/c++/4.8.1/cstdlib:135:11: error: ‘::exit’ has not been declared
   using ::exit;
           ^
/usr/include/c++/4.8.1/cstdlib:136:11: error: ‘::free’ has not been declared
   using ::free;
           ^
/usr/include/c++/4.8.1/cstdlib:137:11: error: ‘::getenv’ has not been declared
   using ::getenv;
           ^
/usr/include/c++/4.8.1/cstdlib:138:11: error: ‘::labs’ has not been declared
   using ::labs;
           ^
/usr/include/c++/4.8.1/cstdlib:139:11: error: ‘::ldiv’ has not been declared
   using ::ldiv;
           ^
/usr/include/c++/4.8.1/cstdlib:140:11: error: ‘::malloc’ has not been declared
   using ::malloc;
           ^
/usr/include/c++/4.8.1/cstdlib:142:11: error: ‘::mblen’ has not been declared
   using ::mblen;
           ^
/usr/include/c++/4.8.1/cstdlib:143:11: error: ‘::mbstowcs’ has not been declared
   using ::mbstowcs;
           ^
/usr/include/c++/4.8.1/cstdlib:144:11: error: ‘::mbtowc’ has not been declared
   using ::mbtowc;
           ^
/usr/include/c++/4.8.1/cstdlib:146:11: error: ‘::qsort’ has not been declared
   using ::qsort;
           ^
/usr/include/c++/4.8.1/cstdlib:152:11: error: ‘::rand’ has not been declared
   using ::rand;
           ^
/usr/include/c++/4.8.1/cstdlib:153:11: error: ‘::realloc’ has not been declared
   using ::realloc;
           ^
/usr/include/c++/4.8.1/cstdlib:154:11: error: ‘::srand’ has not been declared
   using ::srand;
           ^
/usr/include/c++/4.8.1/cstdlib:155:11: error: ‘::strtod’ has not been declared
   using ::strtod;
           ^
/usr/include/c++/4.8.1/cstdlib:156:11: error: ‘::strtol’ has not been declared
   using ::strtol;
           ^
/usr/include/c++/4.8.1/cstdlib:157:11: error: ‘::strtoul’ has not been declared
   using ::strtoul;
           ^
/usr/include/c++/4.8.1/cstdlib:158:11: error: ‘::system’ has not been declared
   using ::system;
           ^
/usr/include/c++/4.8.1/cstdlib:160:11: error: ‘::wcstombs’ has not been declared
   using ::wcstombs;
           ^
/usr/include/c++/4.8.1/cstdlib:161:11: error: ‘::wctomb’ has not been declared
   using ::wctomb;
           ^
/usr/include/c++/4.8.1/cstdlib:168:10: error: ‘ldiv_t’ does not name a type
   inline ldiv_t
          ^
/usr/include/c++/4.8.1/cstdlib:201:11: error: ‘::lldiv_t’ has not been declared
   using ::lldiv_t;
           ^
/usr/include/c++/4.8.1/cstdlib:207:11: error: ‘::_Exit’ has not been declared
   using ::_Exit;
           ^
/usr/include/c++/4.8.1/cstdlib:211:11: error: ‘::llabs’ has not been declared
   using ::llabs;
           ^
/usr/include/c++/4.8.1/cstdlib:213:10: error: ‘lldiv_t’ does not name a type
   inline lldiv_t
          ^
/usr/include/c++/4.8.1/cstdlib:217:11: error: ‘::lldiv’ has not been declared
   using ::lldiv;
           ^
/usr/include/c++/4.8.1/cstdlib:228:11: error: ‘::atoll’ has not been declared
   using ::atoll;
           ^
/usr/include/c++/4.8.1/cstdlib:229:11: error: ‘::strtoll’ has not been declared
   using ::strtoll;
           ^
/usr/include/c++/4.8.1/cstdlib:230:11: error: ‘::strtoull’ has not been declared
   using ::strtoull;
           ^
/usr/include/c++/4.8.1/cstdlib:232:11: error: ‘::strtof’ has not been declared
   using ::strtof;
           ^
/usr/include/c++/4.8.1/cstdlib:233:11: error: ‘::strtold’ has not been declared
   using ::strtold;
           ^
/usr/include/c++/4.8.1/cstdlib:241:22: error: ‘__gnu_cxx::lldiv_t’ has not been declared
   using ::__gnu_cxx::lldiv_t;
                      ^
/usr/include/c++/4.8.1/cstdlib:243:22: error: ‘__gnu_cxx::_Exit’ has not been declared
   using ::__gnu_cxx::_Exit;
                      ^
/usr/include/c++/4.8.1/cstdlib:245:22: error: ‘__gnu_cxx::llabs’ has not been declared
   using ::__gnu_cxx::llabs;
                      ^
/usr/include/c++/4.8.1/cstdlib:246:22: error: ‘__gnu_cxx::div’ has not been declared
   using ::__gnu_cxx::div;
                      ^
/usr/include/c++/4.8.1/cstdlib:247:22: error: ‘__gnu_cxx::lldiv’ has not been declared
   using ::__gnu_cxx::lldiv;
                      ^
/usr/include/c++/4.8.1/cstdlib:249:22: error: ‘__gnu_cxx::atoll’ has not been declared
   using ::__gnu_cxx::atoll;
                      ^
/usr/include/c++/4.8.1/cstdlib:250:22: error: ‘__gnu_cxx::strtof’ has not been declared
   using ::__gnu_cxx::strtof;
                      ^
/usr/include/c++/4.8.1/cstdlib:251:22: error: ‘__gnu_cxx::strtoll’ has not been declared
   using ::__gnu_cxx::strtoll;
                      ^
/usr/include/c++/4.8.1/cstdlib:252:22: error: ‘__gnu_cxx::strtoull’ has not been declared
   using ::__gnu_cxx::strtoull;
                      ^
/usr/include/c++/4.8.1/cstdlib:253:22: error: ‘__gnu_cxx::strtold’ has not been declared
   using ::__gnu_cxx::strtold;
                      ^
In file included from main.cpp:2:0:
/usr/include/c++/4.8.1/cstdio:95:11: error: ‘::FILE’ has not been declared
   using ::FILE;
           ^
/usr/include/c++/4.8.1/cstdio:96:11: error: ‘::fpos_t’ has not been declared
   using ::fpos_t;
           ^
/usr/include/c++/4.8.1/cstdio:98:11: error: ‘::clearerr’ has not been declared
   using ::clearerr;
           ^
/usr/include/c++/4.8.1/cstdio:99:11: error: ‘::fclose’ has not been declared
   using ::fclose;
           ^
/usr/include/c++/4.8.1/cstdio:100:11: error: ‘::feof’ has not been declared
   using ::feof;
           ^
/usr/include/c++/4.8.1/cstdio:101:11: error: ‘::ferror’ has not been declared
   using ::ferror;
           ^
/usr/include/c++/4.8.1/cstdio:102:11: error: ‘::fflush’ has not been declared
   using ::fflush;
           ^
/usr/include/c++/4.8.1/cstdio:103:11: error: ‘::fgetc’ has not been declared
   using ::fgetc;
           ^
/usr/include/c++/4.8.1/cstdio:104:11: error: ‘::fgetpos’ has not been declared
   using ::fgetpos;
           ^
/usr/include/c++/4.8.1/cstdio:105:11: error: ‘::fgets’ has not been declared
   using ::fgets;
           ^
/usr/include/c++/4.8.1/cstdio:106:11: error: ‘::fopen’ has not been declared
   using ::fopen;
           ^
/usr/include/c++/4.8.1/cstdio:107:11: error: ‘::fprintf’ has not been declared
   using ::fprintf;
           ^
/usr/include/c++/4.8.1/cstdio:108:11: error: ‘::fputc’ has not been declared
   using ::fputc;
           ^
/usr/include/c++/4.8.1/cstdio:109:11: error: ‘::fputs’ has not been declared
   using ::fputs;
           ^
/usr/include/c++/4.8.1/cstdio:110:11: error: ‘::fread’ has not been declared
   using ::fread;
           ^
/usr/include/c++/4.8.1/cstdio:111:11: error: ‘::freopen’ has not been declared
   using ::freopen;
           ^
/usr/include/c++/4.8.1/cstdio:112:11: error: ‘::fscanf’ has not been declared
   using ::fscanf;
           ^
/usr/include/c++/4.8.1/cstdio:113:11: error: ‘::fseek’ has not been declared
   using ::fseek;
           ^
/usr/include/c++/4.8.1/cstdio:114:11: error: ‘::fsetpos’ has not been declared
   using ::fsetpos;
           ^
/usr/include/c++/4.8.1/cstdio:115:11: error: ‘::ftell’ has not been declared
   using ::ftell;
           ^
/usr/include/c++/4.8.1/cstdio:116:11: error: ‘::fwrite’ has not been declared
   using ::fwrite;
           ^
/usr/include/c++/4.8.1/cstdio:117:11: error: ‘::getc’ has not been declared
   using ::getc;
           ^
/usr/include/c++/4.8.1/cstdio:118:11: error: ‘::getchar’ has not been declared
   using ::getchar;
           ^
/usr/include/c++/4.8.1/cstdio:119:11: error: ‘::gets’ has not been declared
   using ::gets;
           ^
/usr/include/c++/4.8.1/cstdio:120:11: error: ‘::perror’ has not been declared
   using ::perror;
           ^
/usr/include/c++/4.8.1/cstdio:121:11: error: ‘::printf’ has not been declared
   using ::printf;
           ^
/usr/include/c++/4.8.1/cstdio:122:11: error: ‘::putc’ has not been declared
   using ::putc;
           ^
/usr/include/c++/4.8.1/cstdio:123:11: error: ‘::putchar’ has not been declared
   using ::putchar;
           ^
/usr/include/c++/4.8.1/cstdio:124:11: error: ‘::puts’ has not been declared
   using ::puts;
           ^
/usr/include/c++/4.8.1/cstdio:125:11: error: ‘::remove’ has not been declared
   using ::remove;
           ^
/usr/include/c++/4.8.1/cstdio:126:11: error: ‘::rename’ has not been declared
   using ::rename;
           ^
/usr/include/c++/4.8.1/cstdio:127:11: error: ‘::rewind’ has not been declared
   using ::rewind;
           ^
/usr/include/c++/4.8.1/cstdio:128:11: error: ‘::scanf’ has not been declared
   using ::scanf;
           ^
/usr/include/c++/4.8.1/cstdio:129:11: error: ‘::setbuf’ has not been declared
   using ::setbuf;
           ^
/usr/include/c++/4.8.1/cstdio:130:11: error: ‘::setvbuf’ has not been declared
   using ::setvbuf;
           ^
/usr/include/c++/4.8.1/cstdio:131:11: error: ‘::sprintf’ has not been declared
   using ::sprintf;
           ^
/usr/include/c++/4.8.1/cstdio:132:11: error: ‘::sscanf’ has not been declared
   using ::sscanf;
           ^
/usr/include/c++/4.8.1/cstdio:133:11: error: ‘::tmpfile’ has not been declared
   using ::tmpfile;
           ^
/usr/include/c++/4.8.1/cstdio:134:11: error: ‘::tmpnam’ has not been declared
   using ::tmpnam;
           ^
/usr/include/c++/4.8.1/cstdio:135:11: error: ‘::ungetc’ has not been declared
   using ::ungetc;
           ^
/usr/include/c++/4.8.1/cstdio:136:11: error: ‘::vfprintf’ has not been declared
   using ::vfprintf;
           ^
/usr/include/c++/4.8.1/cstdio:137:11: error: ‘::vprintf’ has not been declared
   using ::vprintf;
           ^
/usr/include/c++/4.8.1/cstdio:138:11: error: ‘::vsprintf’ has not been declared
   using ::vsprintf;
           ^
/usr/include/c++/4.8.1/cstdio:167:11: error: ‘::snprintf’ has not been declared
   using ::snprintf;
           ^
/usr/include/c++/4.8.1/cstdio:168:11: error: ‘::vfscanf’ has not been declared
   using ::vfscanf;
           ^
/usr/include/c++/4.8.1/cstdio:169:11: error: ‘::vscanf’ has not been declared
   using ::vscanf;
           ^
/usr/include/c++/4.8.1/cstdio:170:11: error: ‘::vsnprintf’ has not been declared
   using ::vsnprintf;
           ^
/usr/include/c++/4.8.1/cstdio:171:11: error: ‘::vsscanf’ has not been declared
   using ::vsscanf;
           ^
/usr/include/c++/4.8.1/cstdio:177:22: error: ‘__gnu_cxx::snprintf’ has not been declared
   using ::__gnu_cxx::snprintf;
                      ^
/usr/include/c++/4.8.1/cstdio:178:22: error: ‘__gnu_cxx::vfscanf’ has not been declared
   using ::__gnu_cxx::vfscanf;
                      ^
/usr/include/c++/4.8.1/cstdio:179:22: error: ‘__gnu_cxx::vscanf’ has not been declared
   using ::__gnu_cxx::vscanf;
                      ^
/usr/include/c++/4.8.1/cstdio:180:22: error: ‘__gnu_cxx::vsnprintf’ has not been declared
   using ::__gnu_cxx::vsnprintf;
                      ^
/usr/include/c++/4.8.1/cstdio:181:22: error: ‘__gnu_cxx::vsscanf’ has not been declared
   using ::__gnu_cxx::vsscanf;
                      ^
main.cpp: In function ‘int main(int, char**)’:
main.cpp:12:22: error: ‘printf’ was not declared in this scope
     printf("nUsage:");
                      ^
main.cpp:14:11: error: ‘exit’ was not declared in this scope
     exit(0);
           ^

Last edited by MisterEwok (2013-08-29 10:15:07)

#2 2013-08-28 22:18:35

MisterEwok
Member
Registered: 2013-08-28
Posts: 38

Re: g++ isn’t compiling!

I’ve already tried force removing and reinstalling gcc and gcc-libs, with no change.

#3 2013-08-29 01:07:10

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 27,833
Website

Re: g++ isn’t compiling!

Is gcc also not compiling?  If gcc works on a c file, you should probably change the title to specify g++ as all the issues are c++ lib related.


«UNIX is simple and coherent…» — Dennis Ritchie, «GNU’s Not UNIX» —  Richard Stallman

#4 2013-08-29 01:12:10

at0m5k
Member
Registered: 2013-07-22
Posts: 40
Website

Re: g++ isn’t compiling!

These look like linking errors. Make sure that all of your headers are defined explicitly (just to be sure). Then make sure that you are using the std namespace i.e using namespace std;.

#5 2013-08-29 10:16:29

MisterEwok
Member
Registered: 2013-08-28
Posts: 38

Re: g++ isn’t compiling!

@Trilby: compiling and linking work with a simple .c program so I changed the title

@at0m5k: The -c flag means I’m only trying to compile in the above paste.

#6 2013-08-29 10:24:25

MisterEwok
Member
Registered: 2013-08-28
Posts: 38

Re: g++ isn’t compiling!

Like I said, I have never had this problem until two days ago.

When I change the includes to

#include <stdlib.h>
#include <stdio.h>

instead of

#include <cstdlib>
#include <cstdio>

as I originally had it, I get this:

g++ -c main.cpp
main.cpp: In function ‘int main(int, char**)’:
main.cpp:12:22: error: ‘printf’ was not declared in this scope
     printf("nUsage:");
                      ^
main.cpp:14:11: error: ‘exit’ was not declared in this scope
     exit(0);
           ^

And these lines are also at the end of the first paste.

#7 2013-08-29 10:40:25

Allan
Pacman
From: Brisbane, AU
Registered: 2007-06-09
Posts: 11,246
Website

Re: g++ isn’t compiling!

Show us the code…

#8 2013-08-29 10:43:22

MisterEwok
Member
Registered: 2013-08-28
Posts: 38

Re: g++ isn’t compiling!

#include <stdlib.h>
#include <stdio.h>
#include "matrixOps.h"

using namespace std;

int main(int argsc, char* Args[])
{
  /* Check for correct number of arguments (output file not required; defaults to "RESULT.mat") */
  if (argsc < 3)
  {
    printf("nUsage:");
    printf("nMultMatrices first_matrix_file second_matrix_file output_file(optional)nn");
    exit(0);
  }
  
  //declare variables (three matrices and their respective dimensions)
  double **A, **B, **C;
  int Arows, Acols, Brows, Bcols, Crows, Ccols;
  
  //Populate Matrices A and B from first two file arguments
  readMatrix(Args[1],A,Arows,Acols);
  readMatrix(Args[2],B,Brows,Bcols);
  
  //Populate Matrix C by multiplying A and B
  mat_mat_multiply(A,Arows,Acols,B,Brows,Bcols,C,Crows,Ccols);
  
  //Write the resultant C matrix to the third file argument
  writeMatrix(Args[3],C,Crows,Ccols);

  return 0;
}

#9 2013-08-29 10:53:31

WorMzy
Forum Moderator
From: Scotland
Registered: 2010-06-16
Posts: 11,018
Website

Re: g++ isn’t compiling!

Could you check that your filesystem isn’t corrupted by checking the filetype and size of the include files. e.g.

$ file /usr/include/c++/4.8.1/cstdio
/usr/include/c++/4.8.1/cstdio: C source, ASCII text

$ du /usr/include/c++/4.8.1/cstdio 
8       /usr/include/c++/4.8.1/cstdio

Sakura:-
Mobo: MSI MAG X570S TORPEDO MAX // Processor: AMD Ryzen 9 5950X @4.9GHz // GFX: AMD Radeon RX 5700 XT // RAM: 32GB (4x 8GB) Corsair DDR4 (@ 3000MHz) // Storage: 1x 3TB HDD, 6x 1TB SSD, 2x 120GB SSD, 1x 275GB M2 SSD

Making lemonade from lemons since 2015.

#10 2013-08-29 10:58:06

Allan
Pacman
From: Brisbane, AU
Registered: 2007-06-09
Posts: 11,246
Website

Re: g++ isn’t compiling!

MisterEwok wrote:

#include <stdlib.h>
#include <stdio.h>

Use cstdlib.h instead of stdlib.h ,etc

#11 2013-08-29 11:40:55

MisterEwok
Member
Registered: 2013-08-28
Posts: 38

Re: g++ isn’t compiling!

@Allan:

 g++ -c main.cpp
main.cpp:1:21: fatal error: cstdlib.h: No such file or directory
 #include <cstdlib.h>
                     ^
compilation terminated.

@WorMsy

$ file /usr/include/c++/4.8.1/cstdio
/usr/include/c++/4.8.1/cstdio: C source, ASCII text
$ du /usr/include/c++/4.8.1/cstdio
8	/usr/include/c++/4.8.1/cstdio

#12 2013-08-29 23:08:33

Allan
Pacman
From: Brisbane, AU
Registered: 2007-06-09
Posts: 11,246
Website

Re: g++ isn’t compiling!

I should have said «#include <cstdlib>»

#13 2013-08-30 11:58:43

MisterEwok
Member
Registered: 2013-08-28
Posts: 38

Re: g++ isn’t compiling!

@Allan: That’s what I had in the first place; see original post.

#14 2013-08-30 12:08:05

Allan
Pacman
From: Brisbane, AU
Registered: 2007-06-09
Posts: 11,246
Website

Re: g++ isn’t compiling!

Can you give us a more minimal example without a mystery header so we can actually try compiling it ourselves?

#15 2013-08-30 12:09:32

Allan
Pacman
From: Brisbane, AU
Registered: 2007-06-09
Posts: 11,246
Website

Re: g++ isn’t compiling!

Also run «pacman -Qkk» on gcc and glibc to check all files are fine.

#16 2013-08-30 12:36:27

MisterEwok
Member
Registered: 2013-08-28
Posts: 38

Re: g++ isn’t compiling!

Here’s a hello code:

#include <cstdio>

using namespace std;

int main ()
{
  printf("nHello world!nn");
  
  return 0;
}

Compiling gives:

$ g++ -c hello.cpp 
In file included from hello.cpp:1:0:
/usr/include/c++/4.8.1/cstdio:95:11: error: ‘::FILE’ has not been declared
   using ::FILE;
           ^
/usr/include/c++/4.8.1/cstdio:96:11: error: ‘::fpos_t’ has not been declared
   using ::fpos_t;
           ^
/usr/include/c++/4.8.1/cstdio:98:11: error: ‘::clearerr’ has not been declared
   using ::clearerr;
           ^
/usr/include/c++/4.8.1/cstdio:99:11: error: ‘::fclose’ has not been declared
   using ::fclose;
           ^
/usr/include/c++/4.8.1/cstdio:100:11: error: ‘::feof’ has not been declared
   using ::feof;
           ^
/usr/include/c++/4.8.1/cstdio:101:11: error: ‘::ferror’ has not been declared
   using ::ferror;
           ^
/usr/include/c++/4.8.1/cstdio:102:11: error: ‘::fflush’ has not been declared
   using ::fflush;
           ^
/usr/include/c++/4.8.1/cstdio:103:11: error: ‘::fgetc’ has not been declared
   using ::fgetc;
           ^
/usr/include/c++/4.8.1/cstdio:104:11: error: ‘::fgetpos’ has not been declared
   using ::fgetpos;
           ^
/usr/include/c++/4.8.1/cstdio:105:11: error: ‘::fgets’ has not been declared
   using ::fgets;
           ^
/usr/include/c++/4.8.1/cstdio:106:11: error: ‘::fopen’ has not been declared
   using ::fopen;
           ^
/usr/include/c++/4.8.1/cstdio:107:11: error: ‘::fprintf’ has not been declared
   using ::fprintf;
           ^
/usr/include/c++/4.8.1/cstdio:108:11: error: ‘::fputc’ has not been declared
   using ::fputc;
           ^
/usr/include/c++/4.8.1/cstdio:109:11: error: ‘::fputs’ has not been declared
   using ::fputs;
           ^
/usr/include/c++/4.8.1/cstdio:110:11: error: ‘::fread’ has not been declared
   using ::fread;
           ^
/usr/include/c++/4.8.1/cstdio:111:11: error: ‘::freopen’ has not been declared
   using ::freopen;
           ^
/usr/include/c++/4.8.1/cstdio:112:11: error: ‘::fscanf’ has not been declared
   using ::fscanf;
           ^
/usr/include/c++/4.8.1/cstdio:113:11: error: ‘::fseek’ has not been declared
   using ::fseek;
           ^
/usr/include/c++/4.8.1/cstdio:114:11: error: ‘::fsetpos’ has not been declared
   using ::fsetpos;
           ^
/usr/include/c++/4.8.1/cstdio:115:11: error: ‘::ftell’ has not been declared
   using ::ftell;
           ^
/usr/include/c++/4.8.1/cstdio:116:11: error: ‘::fwrite’ has not been declared
   using ::fwrite;
           ^
/usr/include/c++/4.8.1/cstdio:117:11: error: ‘::getc’ has not been declared
   using ::getc;
           ^
/usr/include/c++/4.8.1/cstdio:118:11: error: ‘::getchar’ has not been declared
   using ::getchar;
           ^
/usr/include/c++/4.8.1/cstdio:119:11: error: ‘::gets’ has not been declared
   using ::gets;
           ^
/usr/include/c++/4.8.1/cstdio:120:11: error: ‘::perror’ has not been declared
   using ::perror;
           ^
/usr/include/c++/4.8.1/cstdio:121:11: error: ‘::printf’ has not been declared
   using ::printf;
           ^
/usr/include/c++/4.8.1/cstdio:122:11: error: ‘::putc’ has not been declared
   using ::putc;
           ^
/usr/include/c++/4.8.1/cstdio:123:11: error: ‘::putchar’ has not been declared
   using ::putchar;
           ^
/usr/include/c++/4.8.1/cstdio:124:11: error: ‘::puts’ has not been declared
   using ::puts;
           ^
/usr/include/c++/4.8.1/cstdio:125:11: error: ‘::remove’ has not been declared
   using ::remove;
           ^
/usr/include/c++/4.8.1/cstdio:126:11: error: ‘::rename’ has not been declared
   using ::rename;
           ^
/usr/include/c++/4.8.1/cstdio:127:11: error: ‘::rewind’ has not been declared
   using ::rewind;
           ^
/usr/include/c++/4.8.1/cstdio:128:11: error: ‘::scanf’ has not been declared
   using ::scanf;
           ^
/usr/include/c++/4.8.1/cstdio:129:11: error: ‘::setbuf’ has not been declared
   using ::setbuf;
           ^
/usr/include/c++/4.8.1/cstdio:130:11: error: ‘::setvbuf’ has not been declared
   using ::setvbuf;
           ^
/usr/include/c++/4.8.1/cstdio:131:11: error: ‘::sprintf’ has not been declared
   using ::sprintf;
           ^
/usr/include/c++/4.8.1/cstdio:132:11: error: ‘::sscanf’ has not been declared
   using ::sscanf;
           ^
/usr/include/c++/4.8.1/cstdio:133:11: error: ‘::tmpfile’ has not been declared
   using ::tmpfile;
           ^
/usr/include/c++/4.8.1/cstdio:134:11: error: ‘::tmpnam’ has not been declared
   using ::tmpnam;
           ^
/usr/include/c++/4.8.1/cstdio:135:11: error: ‘::ungetc’ has not been declared
   using ::ungetc;
           ^
/usr/include/c++/4.8.1/cstdio:136:11: error: ‘::vfprintf’ has not been declared
   using ::vfprintf;
           ^
/usr/include/c++/4.8.1/cstdio:137:11: error: ‘::vprintf’ has not been declared
   using ::vprintf;
           ^
/usr/include/c++/4.8.1/cstdio:138:11: error: ‘::vsprintf’ has not been declared
   using ::vsprintf;
           ^
/usr/include/c++/4.8.1/cstdio:167:11: error: ‘::snprintf’ has not been declared
   using ::snprintf;
           ^
/usr/include/c++/4.8.1/cstdio:168:11: error: ‘::vfscanf’ has not been declared
   using ::vfscanf;
           ^
/usr/include/c++/4.8.1/cstdio:169:11: error: ‘::vscanf’ has not been declared
   using ::vscanf;
           ^
/usr/include/c++/4.8.1/cstdio:170:11: error: ‘::vsnprintf’ has not been declared
   using ::vsnprintf;
           ^
/usr/include/c++/4.8.1/cstdio:171:11: error: ‘::vsscanf’ has not been declared
   using ::vsscanf;
           ^
/usr/include/c++/4.8.1/cstdio:177:22: error: ‘__gnu_cxx::snprintf’ has not been declared
   using ::__gnu_cxx::snprintf;
                      ^
/usr/include/c++/4.8.1/cstdio:178:22: error: ‘__gnu_cxx::vfscanf’ has not been declared
   using ::__gnu_cxx::vfscanf;
                      ^
/usr/include/c++/4.8.1/cstdio:179:22: error: ‘__gnu_cxx::vscanf’ has not been declared
   using ::__gnu_cxx::vscanf;
                      ^
/usr/include/c++/4.8.1/cstdio:180:22: error: ‘__gnu_cxx::vsnprintf’ has not been declared
   using ::__gnu_cxx::vsnprintf;
                      ^
/usr/include/c++/4.8.1/cstdio:181:22: error: ‘__gnu_cxx::vsscanf’ has not been declared
   using ::__gnu_cxx::vsscanf;
                      ^
hello.cpp: In function ‘int main()’:
hello.cpp:7:30: error: ‘printf’ was not declared in this scope
   printf("nHello world!nn");
                              ^

#17 2013-08-30 12:40:05

MisterEwok
Member
Registered: 2013-08-28
Posts: 38

Re: g++ isn’t compiling!

$ pacman -Qkk gcc glibc
gcc: 1938 total files, 0 altered files
warning: glibc: /etc/gai.conf (Modification time mismatch)
warning: glibc: /etc/locale.gen (Modification time mismatch)
warning: glibc: /etc/locale.gen (Size mismatch)
warning: glibc: /etc/nscd.conf (Modification time mismatch)
glibc: 1503 total files, 3 altered files

#18 2013-08-30 17:16:49

derhamster
Member
Registered: 2012-07-08
Posts: 86

Re: g++ isn’t compiling!

Compile the code in verbose mode:

and post the output. Might be worth looking at the default include directories.

Also, did you try compiling the code with clang?

Edit, with more ideas:
You can generate a list of defined preprocessor macros with:

Its quite long, but someone might still spot some missing or incorrectly defined macros in there.

Do you have any environment variables defined, that affect g++? printenv lists all variables.

Last edited by derhamster (2013-08-30 17:27:30)

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.

Понравилась статья? Поделить с друзьями:
  • Error exists in required projects eclipse
  • Error exist in the active configuration of project
  • Error exfat file system is not found
  • Error execution phase kubelet start error uploading crisocket timed out waiting for the condition
  • Error expected nested name specifier before system