I am trying to port an ARM-C library to be compiled with x86_64 C++, and I am getting the following error:
In file included from /usr/include/c++/5/cwchar:44:0,
from /usr/include/c++/5/bits/postypes.h:40,
from /usr/include/c++/5/bits/char_traits.h:40,
from /usr/include/c++/5/string:40,
from MyFile.h:19,
/usr/include/wchar.h:226:20: error: initializer provided for function
__THROW __asm ("wcschr") __attribute_pure__;
^
where MyFile.h has the following structure
// comments
#pragma once
// comments
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <string> //<<< line 19
…
Initially, instead of it used to be which gave me a similar error:
In file included from MyFile.h:19:
/usr/include/string.h:73:21: error: initializer provided for function
__THROW __asm ("memchr") __attribute_pure__ __nonnull ((1));
^
Compiler version:
GNU C++14 (Ubuntu 5.4.0-6ubuntu1~16.04.11) version 5.4.0 20160609 (x86_64-linux-gnu)
compiled by GNU C version 5.4.0 20160609, GMP version 6.1.0, MPFR version 3.1.4, MPC version 1.0.3
ldd (Ubuntu GLIBC 2.23-0ubuntu11) 2.23
Compilation flags:
#g++ -O3 -std=c++14 -fpermissive -Wno-system-headers -w
UPDATE 1:
I’ve been modifying the Makefile
, and the original version contains $@.via
. For instance:
@$(COMPILE) -M -MF $(subst .o,.d.tmp,$@) -MT $@ -E $(C_FLAGS) $@.via $< -o $@.preprocessed.c
and I changed the $@.via
for @$@.via
because I saw that in an older project they did it like that. However, if I leave as $@.via
I just get:
SomeFile.c:1:1 fatal error: OneHeader.h: No such file or directory
I am starting to think that my Makefile
is somewhere wrong…
I misunderstood the compiler option… Few lines above, my makefile creates the @.via
files passing DEFINES and INCLUDES
@echo $(patsubst %, '%', $(C_DEFINES)) > $@.via
@echo $(C_INCLUDE) >> $@.via
and those @.via
files are passed as additional arguments for the compilation. While for armcc
the --via
is supported see here, I found that for g++ -according to the gcc doc- the syntax is @<your_file>
. Thus, what @$@.via
does is simply to parse the $@.via
to <your_file>.via
.
Now I am still getting the initializer provided for function
error message.
UPDATE 2:
I found the problem and I explained what happened in the answer section. See below.
-
10-15-2010
#1
Registered User
C++ newbie program full of errors!
Hi! I tryed to write down some code of C++, but i have some problems…
…actually i am in my first 5 programs in C++ so i may have stupid mistakes…Code:
#include <cstdio> #include <cstdlib> #include <iostream> using namespace std; class Data{ private: int age; char name; public: init(); printAll(); }; void init(class Data info)( info.age = 20; info.name = "Vasilis"; } int main(void){ Data info; cout << "Hello there! n"; init(info); // printAll(info); *i will declare this later! return 0; }
and my output is:
Code:
program.cpp:12: error: ISO C++ forbids declaration of �init� with no type program.cpp:13: error: ISO C++ forbids declaration of �printAll� with no type program.cpp:17: error: function �void init(Data)� is initialized like a variableprogram.cpp:17: error: �info� was not declared in this scope program.cpp:18: error: expected constructor, destructor, or type conversion before �.� token program.cpp:19: error: expected declaration before �}� token
so, can anyone help me please…? thanks in advance…
-
10-15-2010
#2
Registered User
When you declare a function or method, it must have a return type.
When you implement a class method outside of the class definition, the method name must be prefixed with the class name, i.e.,
Your method implementation must also exactly match the method definition.
-
10-15-2010
#3
Registered User
Originally Posted by rags_to_riches
When you declare a function or method, it must have a return type.
When you implement a class method outside of the class definition, the method name must be prefixed with the class name, i.e.,Your method implementation must also exactly match the method definition.
so, if i want to «call» the function init from main i would write something like yours, right?
edit:
you mean something like this one?Code:
#include <cstdio> #include <cstdlib> #include <iostream> using namespace std; class Data{ private: int age; char name; public: int init(); void printAll(); }; int Data::init(void)( age = 20; name = "Vasilis"; } void Data::printAll(void){ cout << "Hi!n"; } int main(void){ Data info; cout << "Hello there! n"; info.init(); info.printAll(); //*i will declare this later! return 0; }
Last edited by brack; 10-15-2010 at 07:02 AM.
-
10-15-2010
#4
Registered User
Here is a version of the code that should work
Code:
#include <cstdio> #include <cstdlib> #include <iostream> using namespace std; class Data{ private: int age; char name; public: void init(); void printAll(); }; void Data::init(){ age = 20; name = "Vasilis"; } void Data::printAll(){ cout << age "n"; cout << name "n"; int main(void){ Data info; cout << "Hello there! n"; info.init(); info.printAll(); // i will declare this later! return 0; }
Hope it helped!!!
-
10-16-2010
#5
Registered User
In init function there is this error…
18 C:Userscs091770Desktopversion.cpp invalid conversion from `const char*’ to `char’
In printAll function there is this error…
22 C:Userscs091770Desktopversion.cpp expected `;’ before string constant
23 C:Userscs091770Desktopversion.cpp expected `;’ before string constantCan anyone correct them…?
edit: Just to know i added the «}» that missed!!
-
10-16-2010
#6
Lurking
This is what happens when you accept code from morons who’ve only posted like three times and only like doing people’s homework (badly). Let’s fix what you wrote:
Originally Posted by brack
Code:
#include <cstdio> #include <cstdlib> #include <iostream> using namespace std; class Data{ private: int age; char name; public: int init(); void printAll(); }; int Data::init(void)( age = 20; name = "Vasilis"; } void Data::printAll(void){ cout << "Hi!n"; } int main(void){ Data info; cout << "Hello there! n"; info.init(); info.printAll(); //*i will declare this later! return 0; }
Compiling this I get
Compiling: foo.cpp
C:Documents and SettingsOwnerMy Documentsfoofoo.cpp:16: error: initializer provided for function
C:Documents and SettingsOwnerMy Documentsfoofoo.cpp:18: error: expected constructor, destructor, or type conversion before ‘=’ token
C:Documents and SettingsOwnerMy Documentsfoofoo.cpp:19: error: expected declaration before ‘}’ token
Process terminated with status 1 (0 minutes, 1 seconds)
3 errors, 0 warningsSo what does this mean? Well you usually take it one error at a time. The first error is on line 16, and it says initializer provided for function. Whatever we typed, it is being interpreted as an initializer by the compiler. Except we know that init is a function and not a variable that could be initialized. To fix this, we have to scrutinize the syntax (as we always should). My editor highlights
Code:
void Data::init(void)(
Obviously this parens was meant to be a bracket, so we replace that and recompile.
Now we get
Compiling: foo.cpp
C:Documents and SettingsOwnerMy Documentsfoofoo.cpp: In member function ‘int Data::init()’:
C:Documents and SettingsOwnerMy Documentsfoofoo.cpp:18: error: invalid conversion from ‘const char*’ to ‘char’
C:Documents and SettingsOwnerMy Documentsfoofoo.cpp:19: warning: no return statement in function returning non-void
Process terminated with status 1 (0 minutes, 0 seconds)
1 errors, 1 warningsNow we need to fix both of these. The error would be fixed by changing char name to const char *name, but is that appropriate? By the way name is used, it looks like it is. So we change that and recompile. And if done correctly, you are left with the warning «no return statement in function returning non-void».
That is only related to the init function, as the line number implies. This function looks like it should be a void function to me, so I would change the return type, but you can also return an int if you want.
And then we have correct code! You did it yourself, and learned a lot, I hope.
Last edited by whiteflags; 10-16-2010 at 10:15 AM.
-
10-16-2010
#7
Registered User
i did it!!! thank you so much whiteflags!!!
i sincerely aπpreciate your help!!
-
10-16-2010
#8
C++まいる!Cをこわせ!
I think it is more appropriate that name be a std::string. That way, you can assign and modify it. std::string is, put simply, a C++ string.
It should also avoid pointer pitfalls.Originally Posted by Adak
io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
Originally Posted by Salem
You mean it’s included as a crutch to help ancient programmers limp along without them having to relearn too much.
Outside of your DOS world, your header file is meaningless.
-
10-16-2010
#9
Lurking
Originally Posted by Elysia
I think it is more appropriate that name be a std::string. That way, you can assign and modify it. std::string is, put simply, a C++ string.
It should also avoid pointer pitfalls.It would be more worth it if brack was actually doing string operations. As it is, he can assign to name as many times as he wants and print it.
-
10-16-2010
#10
C++まいる!Cをこわせ!
True that, but I figured it would scale better. Better to learn something that is works all the time and is safe than something that can be error prone and works only half the times.
Originally Posted by Adak
io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
Originally Posted by Salem
You mean it’s included as a crutch to help ancient programmers limp along without them having to relearn too much.
Outside of your DOS world, your header file is meaningless.
-
10-17-2010
#11
Registered User
C++ is newbie to be! You may be right Elysia, i am now learning C++ (tips) so i missed it! i’ ll try modify this…
-
2nd October 2015, 20:31
#1
This is my old system where my program compiles just fine:
qt5-base 5.4.1-2
qt5-declarative 5.4.1-2
qt5-doc 5.4.1-2
qt5-graphicaleffects 5.5.0-2
qt5-location 5.4.1-2
qt5-quick1 5.4.1-2
qt5-quickcontrols 5.4.1-2
qt5-script 5.4.1-2
qt5-sensors 5.4.1-2
qt5-svg 5.4.1-2
qt5-tools 5.4.1-2
qt5-translations 5.4.1-2
qt5-webchannel 5.4.1-2
qt5-webkit 5.4.1-2
qt5-xmlpatterns 5.4.1-2
qtchooser 48-1
qtcreator 3.3.2-1
To copy to clipboard, switch view to plain text mode
After the update:
qt5-base 5.5.0-2
qt5-declarative 5.5.0-2
qt5-doc 5.5.0-2
qt5-graphicaleffects 5.5.0-2
qt5-location 5.5.0-2
qt5-quick1 5.5.0-2
qt5-quickcontrols 5.5.0-2
qt5-script 5.5.0-2
qt5-sensors 5.5.0-2
qt5-svg 5.5.0-2
qt5-tools 5.5.0-2
qt5-translations 5.5.0-2
qt5-webchannel 5.5.0-2
qt5-webkit 5.5.0-2
qt5-xmlpatterns 5.5.0-2
qtchooser 48-1
qtcreator 3.5.0-1
To copy to clipboard, switch view to plain text mode
This is the error I get:
17:23:23: Running steps for project graphit...
17:23:23: Configuration unchanged, skipping qmake step.
17:23:23: Starting: "/usr/bin/make"
g++ -c -pipe -std=c++11 -O2 -march=x86-64 -mtune=generic -O2 -pipe -fstack-protector-strong --param=ssp-buffer-size=4 -std=c++0x -Wall -W -D_REENTRANT -fPIC -DQT_NO_DEBUG -DQT_QUICK_LIB -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_QML_LIB -DQT_NETWORK_LIB -DQT_CORE_LIB -I. -Iinclude -Iinclude/knowdesk -Ilibs -Ilibs -Ipodofo/include -Iexif/include -Iexif/include -isystem /usr/include/qt -isystem /usr/include/qt/QtQuick -isystem /usr/include/qt/QtWidgets -isystem /usr/include/qt/QtGui -isystem /usr/include/qt/QtQml -isystem /usr/include/qt/QtNetwork -isystem /usr/include/qt/QtCore -Ibuild -I/usr/lib/qt/mkspecs/linux-g++ -o build/controller.o src/controller.cpp
In file included from /usr/include/qt/QtCore/qglobal.h:74:0,
from /usr/include/qt/QtCore/qnamespace.h:37,
from /usr/include/qt/QtCore/qobjectdefs.h:41,
from /usr/include/qt/QtCore/qobject.h:40,
from /usr/include/qt/QtCore/QObject:1,
from src/controller.cpp:2:
/usr/include/qt/QtCore/qurl.h:365:1: error: initializer provided for function
Q_DECLARE_SHARED(QUrl)
^
Makefile:975: recipe for target 'build/controller.o' failed
make: *** [build/controller.o] Error 1
17:23:26: The process "/usr/bin/make" exited with code 2.
Error while building/deploying project graphit (kit: Desktop)
When executing step "Make"
17:23:26: Elapsed time: 00:03.
To copy to clipboard, switch view to plain text mode
It seems like it fails compiling as soon as I include anything Q* in a .cpp file. Even if I remove the statements from src/controller.cpp, a similar error gets thrown in the next file where I include Q*. In it’s always «initializer provided for function». A new project compiles fine and I can’t pinpoint anything that causes the error in my project. Does anyone have an idea what causes the problem? I’m pretty desperate at this point, any help will be appreciated. I can also upload the source files if the error is too ambiguous.
-
3rd October 2015, 04:27
#2
Re: Program won’t compile since update from Qt5.4 to Qt5.5 | Error in Qt files?
What are the first 5-10 lines of src/controller.cpp? If line 1 is an include of controller.h or something else from your sources then that file would be useful to see.
What version of GCC?
Are you doing a clean rebuild without any pre-compiled header lying about?
-
4th October 2015, 02:32
#3
Re: Program won’t compile since update from Qt5.4 to Qt5.5 | Error in Qt files?
controller.cpp
#include "controller.h"
#include <QObject>
#include <QString>
#include <QVariant>
#include <QVariantList>
#include <QVariantMap>
#include <string>
#include <vector>
#include "controller.h"
#include "itemcontroller.h"
#include "modelcontroller.h"
#include "knowdesk/knowledgeDB.h"
#include "templatecontroller.h"
#include "filecontroller.h"
#include "libs/easylogging++.h"
void Controller::setQuery(QueryController* q) {
query = q;
}
QueryController* Controller::getQuery() {
return query;
}
.
.
.
To copy to clipboard, switch view to plain text mode
controller.h
#ifndef CONTROLLER_H
#define CONTROLLER_H
class QueryController;
class FileController;
class ModelController;
class TemplateController;
class ItemController;
class KnowledgeDB;
class Controller {
public:
void setQuery(QueryController*);
QueryController* getQuery();
void setFile(FileController*);
FileController* getFile();
void setModel(ModelController*);
ModelController* getModel();
void setTemplate(TemplateController*);
TemplateController* getTemplate();
void setItem(ItemController*);
ItemController* getItem();
void setDB(KnowledgeDB*);
KnowledgeDB* getDB();
private:
QueryController* query;
FileController* file;
ModelController* model;
TemplateController* template_;
ItemController* item;
KnowledgeDB* db;
};
#endif // CONTROLLER_H
To copy to clipboard, switch view to plain text mode
I don’t actually use any of the Q* in controller.cpp. If I remove the #include <Q*> statements, this error will be thrown in the next Header File that attempts to include Q*, itemcontroller.h:
02:25:07: Running steps for project graphit...
02:25:07: Configuration unchanged, skipping qmake step.
02:25:07: Starting: "/usr/bin/make"
g++ -c -pipe -std=c++11 -O2 -march=x86-64 -mtune=generic -O2 -pipe -fstack-protector-strong --param=ssp-buffer-size=4 -std=c++0x -Wall -W -D_REENTRANT -fPIC -DQT_NO_DEBUG -DQT_QUICK_LIB -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_QML_LIB -DQT_NETWORK_LIB -DQT_CORE_LIB -I. -Iinclude -Iinclude/knowdesk -Ilibs -Ilibs -Ipodofo/include -Iexif/include -Iexif/include -isystem /usr/include/qt -isystem /usr/include/qt/QtQuick -isystem /usr/include/qt/QtWidgets -isystem /usr/include/qt/QtGui -isystem /usr/include/qt/QtQml -isystem /usr/include/qt/QtNetwork -isystem /usr/include/qt/QtCore -Ibuild -I/usr/lib/qt/mkspecs/linux-g++ -o build/controller.o src/controller.cpp
In file included from /usr/include/qt/QtCore/qglobal.h:74:0,
from /usr/include/qt/QtCore/qnamespace.h:37,
from /usr/include/qt/QtCore/qobjectdefs.h:41,
from /usr/include/qt/QtCore/qobject.h:40,
from /usr/include/qt/QtCore/QObject:1,
from include/itemcontroller.h:4,
from src/controller.cpp:6:
/usr/include/qt/QtCore/qurl.h:365:1: error: initializer provided for function
Q_DECLARE_SHARED(QUrl)
^
Makefile:975: recipe for target 'build/controller.o' failed
make: *** [build/controller.o] Error 1
02:25:09: The process "/usr/bin/make" exited with code 2.
Error while building/deploying project graphit (kit: Desktop)
When executing step "Make"
02:25:09: Elapsed time: 00:03.
To copy to clipboard, switch view to plain text mode
I have gcc version 5.2.0 and the same error appears after I delete all build files, rerun qmake and rebuild.
I went back in my repo and found that the point where this compilation error first appears is when I change
QQmlEngine engine;
To copy to clipboard, switch view to plain text mode
to
QtQuickControlsApplication app(argc, argv);
QQmlApplicationEngine engine;
To copy to clipboard, switch view to plain text mode
But even after changing this in back in the main.cpp file, or even commenting everything there out, it fails much at other files. So I’m not sure if this relates.
-
6th October 2015, 11:56
#4
Re: Program won’t compile since update from Qt5.4 to Qt5.5 | Error in Qt files?
Here are the source files: http://ge.tt/13W34MP2/v/0
You need SQLite and QtCreator as I haven’t configured it for static build yet.
I can offer to 0.08BTC (around 17€) for anyone who can help me.
BalexD 0 / 0 / 0 Регистрация: 26.05.2013 Сообщений: 16 |
||||
1 |
||||
28.12.2013, 21:41. Показов 30216. Ответов 11 Метки нет (Все метки)
В общем, компилятор почему-то ругается на 3 строку, говоря «expected initializer before void» Что ему тут не нравится — ума не приложу. Все функции есть в хидере, ругаться стал недавно — ранее работал на ура. Перестраивала, перезапускала блокс(на всяк пожарный), а толку нет. Вот сам код:
__________________
0 |
Модератор 12641 / 10135 / 6102 Регистрация: 18.12.2011 Сообщений: 27,170 |
|
28.12.2013, 21:48 |
2 |
Что-то не так в HW_C.h
0 |
1672 / 1044 / 174 Регистрация: 27.09.2009 Сообщений: 1,945 |
|
28.12.2013, 21:48 |
3 |
Логично предположить, что ошибка в файле HW_C.h. Например, отсутствие точки с запятой после определения структуры.
0 |
17 / 17 / 2 Регистрация: 03.05.2013 Сообщений: 114 |
|
28.12.2013, 21:50 |
4 |
Что-то в заголовочном файле не так. Покажите нам его, пожалуйста.
0 |
BalexD 0 / 0 / 0 Регистрация: 26.05.2013 Сообщений: 16 |
||||
28.12.2013, 22:07 [ТС] |
5 |
|||
Вот та самая часть хидера:
0 |
Модератор 12641 / 10135 / 6102 Регистрация: 18.12.2011 Сообщений: 27,170 |
|
29.12.2013, 11:03 |
6 |
У меня это все компилируется.
0 |
0 / 0 / 0 Регистрация: 26.05.2013 Сообщений: 16 |
|
03.01.2014, 02:07 [ТС] |
7 |
Проблема в том, что HW_C.h — один-единственный. И других просто нету. Уж не знаю, на что грешить(
0 |
5493 / 4888 / 831 Регистрация: 04.06.2011 Сообщений: 13,587 |
|
03.01.2014, 02:14 |
8 |
Весь проект выкладывайте.
0 |
0 / 0 / 0 Регистрация: 26.05.2013 Сообщений: 16 |
|
08.01.2014, 20:02 [ТС] |
9 |
Ну, кидаю в виде ссылки. Чтоб никто не терялся: сама функция используется в HW_Dop1.cpp, а в хидере прописана в самом конце.
0 |
5493 / 4888 / 831 Регистрация: 04.06.2011 Сообщений: 13,587 |
|
09.01.2014, 04:58 |
10 |
Вот результат компиляции этого проекта в Code::Blocks 12.11: objDebugHW_Dop1.o||In function `Z13insert_4_numbv’:| И при чём здесь тогда:
компилятор почему-то ругается на 3 строку, говоря «expected initializer before void» ??? Добавлено через 1 минуту
сама функция используется в HW_Dop1.cpp, а в хидере прописана в самом конце.
1 |
0 / 0 / 0 Регистрация: 26.05.2013 Сообщений: 16 |
|
10.01.2014, 00:02 [ТС] |
11 |
Хм.. Странно. У меня все выглядит немного по-другому. А про заголовочный файл скажу, что никто мне не говорил, что так делать нельзя. По крайней мере, до этого момента ошибки не возникало. Что же, учтем и эти грабли. Но спасибо за указания на промахи. Искренне всем благодарна)
0 |
5493 / 4888 / 831 Регистрация: 04.06.2011 Сообщений: 13,587 |
|
10.01.2014, 00:07 |
12 |
Хм.. Странно. У меня все выглядит немного по-другому. Интересно было бы посмотреть.
0 |
Одна из самых неприятных ошибок — это ошибка компиляции для платы Аrduino Nano, с которой вам придется столкнуться не раз.
Содержание
- Синтаксические ошибки
- Ошибки компиляции плат Arduino uno
- Ошибка exit status 1 при компиляции для плат uno, mega и nano
- Ошибки библиотек
- Ошибки компилятора Ардуино
- Основные ошибки
- Ошибка: «avrdude: stk500_recv(): programmer is not responding»
- Ошибка: «a function-definition is not allowed here before ‘{‘ token»
- Ошибка: «No such file or directory / exit status 1»
- Ошибка: «expected initializer before ‘}’ token / expected ‘;’ before ‘}’ token»
- Ошибка: «… was not declared in this scope»
Синтаксические ошибки
Ардуино – одна из наиболее комфортных сред для начинающих инженеров, в особенности программистов, ведь им не приходится проектировать свои системы управления и делать множество других действий.
Сразу же при покупке они получают готовый набор библиотек на С99 и возможность, по необходимости, подтянуть необходимые модули в опен-соурс источниках.
Но и здесь не избежать множества проблем, с которыми знаком каждый программист, и одна из самых неприятных – ошибка компиляции для платы Аrduino nano, с которой вам придется столкнуться не раз. Что же эта строчка означает, какие у неё причины появления, и главное – как быстро решить данную проблему?
Для начала стоит немного окунуться в теорию, чтобы вы понимали причину возникновения данной строчки с текстом и не грешили лишний раз, что Ардуино уно не видит компьютер.
Как несложно догадаться, компиляция – приведение кода на языке Си к виду машинного (двоичного) и преобразование множественных функций в простые операции, чтобы те смогли выполняться через встроенные операнды процессора. Выглядит всё достаточно просто, но сам процесс компиляции происходит значительно сложнее, и поэтому ошибка во время проведения оной может возникать по десяткам причин.
Все мы уже привыкли к тому, что код никогда не запускается с первого раза, и при попытке запустить его в интерпретаторе вылезает десяток ошибок, которые приходится оперативно править. Компилятор действует схожим образом, за исключением того, что причины ошибок указываются далеко не всегда. Именно поэтому рекомендуется протестировать код сначала в среде разработки, и лишь затем уже приступать к его компиляции в исполняемые файлы под Ардуино.
Мы узнали, к чему приводит данный процесс, давайте разберёмся, как он происходит:
- Первое, что делает компилятор – подгружает все инклуднутые файлы, а также меняет объявленные дефайны на значения, которое для них указано. Это необходимо затем, чтобы не нужно было по нескольку раз проходиться синтаксическим парсером в пределах одного кода. Также, в зависимости от среды, компилятор может подставлять функции на место их объявления или делать это уже после прохода синтаксическим парсером. В случае с С99, используется второй вариант реализации, но это и не столь важно.
- Далее он проверяет первичный синтаксис. Этот процесс проводится в изначальном компилируемом файле, и своеобразный парсер ищет, были ли описаны приведенные функции ранее, подключены ли необходимые библиотеки и прочее. Также проверяется правильность приведения типов данных к определенным значениям. Не стоит забывать, что в С99 используется строгая явная типизация, и вы не можете засунуть в строку, объявленную integer, какие-то буквенные значения. Если такое замечается, сразу вылетает ошибка.
- В зависимости от среды разработки, иногда предоставляется возможность последний раз протестировать код, который сейчас будет компилироваться, с запуском интерпретатора соответственно.
- Последним идет стек из различных действий приведения функций, базовых операнд и прочего к двоичному коду, что может занять какое-то время. Также вся структура файлов переносится в исполняемые exe-шники, а затем происходит завершение компиляции.
Как можно увидеть, процесс не так прост, как его рисуют, и на любом этапе может возникнуть какая-то ошибка, которая приведет к остановке компиляции. Проблема в том, что, в отличие от первых трех этапов, баги на последнем – зачастую неявные, но всё ещё не связанные с алгоритмом и логикой программы. Соответственно, их исправление и зачистка занимают значительно больше времени.
А вот синтаксические ошибки – самая частая причина, почему на exit status 1 происходит ошибка компиляции для платы Аrduino nano. Зачастую процесс дебагинга в этом случае предельно простой.
Вам высвечивают ошибку и строчку, а также подсказку от оператора EXCEPTION, что конкретно не понравилось парсеру. Будь то запятая или не закрытые скобки функции, проблема загрузки в плату Аrduino возникнет в любом случае.
Решение предельно простое и логичное – найти и исправить непонравившийся машине синтаксис. Зачастую такие сообщения вылезают пачками, как на этапе тестирования, так и компилирования, поэтому вы можете таким образом «застопорить» разработку не один раз.
Не стоит этого страшиться – этот процесс вполне нормален. Все претензии выводятся на английском, например, часто можно увидеть такое: was not declared in this scope. Что это за ошибка arduino – на самом деле ответ уже скрыт в сообщении. Функция или переменная просто не были задекларированы в области видимости.
Ошибки компиляции плат Arduino uno
Другая частая оплошность пользователя, которая порождает вопросы вроде, что делать, если Аrduino не видит порт, заключается в том, что вы попросту забываете настроить среду разработки. IDE Ардуино создана под все виды плат, но, как мы указывали, на каждом контроллере помещается лишь ограниченное количество библиотек, и их наполнение может быть различным.
Соответственно, если в меню среды вы выбрали компиляцию не под тот МК, то вполне вероятно, что вызываемая вами функция или метод просто не будет найдена в постоянной памяти, вернув ошибку. Стандартно, в настройках указана плата Ардуино уно, поэтому не забывайте её менять. И обратная ситуация может стать причиной, по которой возникает проблема загрузки в плату на Аrduino uno.
Ошибка exit status 1 при компиляции для плат uno, mega и nano
И самое частое сообщение, для пользователей уно, которое выскакивает в среде разработки – exit 1. И оно же самое дискомфортное для отладки приложения, ведь тут необходимо учесть чуть ли не ядро системы, чтобы понять, где же кроется злополучный баг.
В документации указано, что это сообщение указывает на то, что не запускается ide Аrduino в нужной конфигурации, но на деле есть ещё десяток случаев, при которых вы увидите данное сообщение. Однако, действительно, не забывайте проверять разрядность системы, IDE и просматривать, какие библиотеки вам доступны для обращения на текущий момент.
Ошибки библиотек
Если произошла ошибка при компиляции скетча Ардуино, но не выводилось ни одно из вышеописанных сообщений, то можете смело искать баг в библиотеках МК. Это наиболее неприятное занятие для большинства программистов, ведь приходится лазить в чужом коде, но без этого никак.
Ведь банально причина может быть в устаревшем синтаксисе скачанного плагина и, чтобы он заработал, необходимо переписать его практически с нуля. Это единственный выход из сложившейся ситуации. Но бывают и более банальные ситуации, когда вы подключили библиотеку, функции из которой затем ни разу не вызвали, или просто перепутали название.
Ошибки компилятора Ардуино
Ранее упоминался финальный стек действий, при прогонке кода через компилятор, и в этот момент могут произойти наиболее страшные ошибки – баги самого IDE. Здесь конкретного решения быть не может. Вам никто не запрещает залезть в ядро системы и проверить там всё самостоятельно, но куда эффективнее будет откатиться до предыдущей версии программы или, наоборот, обновиться.
Основные ошибки
Ошибка: «avrdude: stk500_recv(): programmer is not responding»
Смотрим какая у нас плата? Какой порт используем? Сообщаем ардуино о правильной плате и порте. Возможно, что используете Nano, а указана Mega. Возможно, что указали неверный порт. Всё это приводит к сообщению: «programmer is not responding».
Решение:
В Arduino IDE в меню «Сервис» выбираем плату. В меню «Сервис → Последовательный порт» выбираем порт.
Ошибка: «a function-definition is not allowed here before ‘{‘ token»
Забыли в коде программы (скетча) закрыть фигурную скобку }.
Решение:
Обычно в Ардуино IDE строка с ошибкой подсвечивается.
Ошибка: «No such file or directory / exit status 1»
Подключаемая библиотека отсутствует в папке libraries.
Решение:
Скачать нужную библиотеку и скопировать её в папку программы — как пример — C:Program FilesArduinolibraries. В случае наличия библиотеки — заменить файлы в папке.
Ошибка: «expected initializer before ‘}’ token / expected ‘;’ before ‘}’ token»
Забыли открыть фигурную скобку {, если видим «initializer before». Ошибка «expected ‘;’ before ‘}’ token» — забыли поставить точку с запятой в конце командной строки.
Решение:
Обычно в Ардуино IDE строка с ошибкой подсвечивается.
Ошибка: «… was not declared in this scope»
Arduino IDE видит в коде выражения или символы, которые не являются служебными или не были объявлены переменными.
Решение:
Проверить код на использование неизвестных выражений или лишних символов.
17 июля 2018 в 13:23
| Обновлено 7 ноября 2020 в 01:20 (редакция)
Опубликовано:
Статьи, Arduino
Я пытаюсь перенести библиотеку ARM-C для компиляции с x86_64 C ++ и получаю следующую ошибку:
In file included from /usr/include/c++/5/cwchar:44:0,
from /usr/include/c++/5/bits/postypes.h:40,
from /usr/include/c++/5/bits/char_traits.h:40,
from /usr/include/c++/5/string:40,
from MyFile.h:19,
/usr/include/wchar.h:226:20: error: initializer provided for function
__THROW __asm ("wcschr") __attribute_pure__;
^
Где MyFile.h имеет следующую структуру
// comments
#pragma once
// comments
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <string> //<<< line 19
…
Изначально вместо него была такая же ошибка:
In file included from MyFile.h:19:
/usr/include/string.h:73:21: error: initializer provided for function
__THROW __asm ("memchr") __attribute_pure__ __nonnull ((1));
^
Версия компилятора:
GNU C++14 (Ubuntu 5.4.0-6ubuntu1~16.04.11) version 5.4.0 20160609 (x86_64-linux-gnu)
compiled by GNU C version 5.4.0 20160609, GMP version 6.1.0, MPFR version 3.1.4, MPC version 1.0.3
ldd (Ubuntu GLIBC 2.23-0ubuntu11) 2.23
Флаги компиляции:
#g++ -O3 -std=c++14 -fpermissive -Wno-system-headers -w
ОБНОВЛЕНИЕ 1:
Я модифицировал Makefile
, и исходная версия содержит $@.via
. Например:
@$(COMPILE) -M -MF $(subst .o,.d.tmp,$@) -MT $@ -E $(C_FLAGS) $@.via $< -o $@.preprocessed.c
И я изменил $@.via
на @$@.via
, потому что я видел, что в более старом проекте они делали это так. Однако, если я уйду как $@.via
, я просто получу:
SomeFile.c:1:1 fatal error: OneHeader.h: No such file or directory
Я начинаю думать, что мой Makefile
где-то не так …
Я неправильно понял параметр компилятора … Несколькими строками выше мой make-файл создает файлы @.via
, передающие DEFINES и INCLUDES
@echo $(patsubst %, '%', $(C_DEFINES)) > $@.via
@echo $(C_INCLUDE) >> $@.via
И эти файлы @.via
передаются в качестве дополнительных аргументов для компиляции. Хотя для armcc
поддерживается --via
см. здесь, я обнаружил, что для g ++ — в соответствии с gcc doc — синтаксис: @<your_file>
. Таким образом, @$@.via
просто анализирует $@.via
на <your_file>.via
.
Теперь я все еще получаю сообщение об ошибке initializer provided for function
.
ОБНОВЛЕНИЕ 2:
Я обнаружил проблему и объяснил, что произошло, в разделе ответов. См. Ниже.
1 ответ
Лучший ответ
Основная причина
Проблема возникла из-за того, что я переопределил __asm
, чтобы заменить его ничем (например, #define __asm
), поскольку я еще не хотел касаться кода сборки. Помните, что я сказал, что портирую ARM на x86, поэтому я подумал, что самый простой способ избавиться от ошибок компиляции — это удалить все эти инструкции __asm
, но не учитывая последствия этого.
Другими словами, когда я включил заголовок string.h
, сам заголовок использует вызов сборки, как указано в сообщении об ошибке:
/usr/include/wchar.h:226:20: error: initializer provided for function
__THROW __asm ("wcschr") __attribute_pure__;
И когда препроцессор изменил __asm("wcschr")
на ("wcschr")
, компилятор обнаруживает ошибку — что имеет смысл.
Мораль истории
Не переопределяйте квалификаторы, так как это также повлияет на другие модули, которые вы не видите напрямую, и предпочитаете создать макрос, чтобы просто изменить их (например, __asm
для /*__asm*/
) или просто запустить sed
в себе кодовая база.
1
Berthin
7 Ноя 2019 в 11:54
- Forum
- Beginners
- Error: Expected initializer before void
Error: Expected initializer before void
Hey guys today, after a long time I was coding in C++ and I got an Error:
Expected initializer before void
Can anyone help?
|
|
int count = 0, length
Missing a semi-colon.
You need a semicolon at the end of line 7.
But should avoid global variables, and always declare one variable per line of code. Delay declaration until you have a sensible value to assign to the variable.
I like to put function declarations before main, with the definitions after:
|
|
I would also avoid changing the original phrase, I made a new variable and changed that instead.
Topic archived. No new replies allowed.
When I try to compile the following code in Arduino ,I get the error «expected initializer before ‘void'».How can I get the code to work?
void setup() {
Serial.begin(9600);
}
float area = 0.0f,pre_area = 0.0f,tarea = 0.0f,rarea = 0.0f;
int x = 0,pre_x = 0,t = 0,pre_t = 0;
long unsigned int t
void loop()
{
x = analogRead(A0);
t = millis();
float diff_t = (float)(t - pre_t)/1000.0f;
area = (0.5 * (pre_x + x) * diff_t) + pre_area;
Serial.print(area);
analogWrite(DAC0, area);
pre_x = x;
pre_area = area;
pre_time = t;
}
asked Aug 26, 2015 at 10:40
1
You add the semicolon that is missing at the end of long unsigned int t
answered Aug 26, 2015 at 10:47
1
Why have you written t = 0 here and declared it again below??
int x = 0,pre_x = 0,t = 0,pre_t = 0;
Semi Colon Missing
long unsigned int t;
Where have you declared pre_time??
pre_time = t;
answered Aug 26, 2015 at 10:49
long unsigned int t
No semicolon.
Plus, make up your mind what type «t» is:
int x = 0,pre_x = 0,t = 0,pre_t = 0;
long unsigned int t;
Is it int
or long unsigned int
?
How can I get the code to work?
Avoid C++ syntax errors.
answered Aug 26, 2015 at 10:53
Nick Gammon♦Nick Gammon
35.7k12 gold badges62 silver badges121 bronze badges
Я получаю эту ошибку во время компиляции (g ++ 4.4.6):
main.cpp: In function ‘int main()’:
main.cpp:27: error: expected initializer before ‘:’ token
main.cpp:33: error: expected primary-expression before ‘for’
main.cpp:33: error: expected ‘;’ before ‘for’
main.cpp:33: error: expected primary-expression before ‘for’
main.cpp:33: error: expected ‘)’ before ‘for’
main.cpp:33: error: expected initializer before ‘:’ token
main.cpp:36: error: could not convert ‘((list != 0u) ? (list->SortedList::~SortedList(), operator delete(((void*)list))) : 0)’ to ‘bool’
main.cpp:37: error: expected primary-expression before ‘return’
main.cpp:37: error: expected ‘)’ before ‘return’
Мой код выглядит следующим образом:
#include <iostream>
#include "Student.h"
#include "SortedList.h"
using namespace std;
int main() {
SortedList *list = new SortedList();
Student create[100];
int num = 100000;
for (Student &x : create) { // <--Line 27
x = new Student(num);
num += 10;
}
for (Student &x : create)
list->insert(&x);
delete list;
return 0;
}
Любой, кто, возможно, знает источник ошибки, будет большим подспорьем. Кроме того, Student и SortedList — это объекты, объявленные в их файлах .h.