Error initializer provided for function

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/...

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.

  1. 10-15-2010


    #1

    brack is offline


    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…


  2. 10-15-2010


    #2

    rags_to_riches is offline


    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.


  3. 10-15-2010


    #3

    brack is offline


    Registered User


    Quote Originally Posted by rags_to_riches
    View Post

    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.


  4. 10-15-2010


    #4

    traitor_651 is offline


    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!!!


  5. 10-16-2010


    #5

    brack is offline


    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 constant

    Can anyone correct them…?

    edit: Just to know i added the «}» that missed!!


  6. 10-16-2010


    #6

    whiteflags is offline


    Lurking

    whiteflags's Avatar


    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:

    Quote Originally Posted by brack
    View Post

    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 warnings

    So 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 warnings

    Now 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.


  7. 10-16-2010


    #7

    brack is offline


    Registered User


    i did it!!! thank you so much whiteflags!!!
    i sincerely aπpreciate your help!!


  8. 10-16-2010


    #8

    Elysia is offline


    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.

    Quote Originally Posted by Adak
    View Post

    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.

    Quote Originally Posted by Salem
    View Post

    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.


  9. 10-16-2010


    #9

    whiteflags is offline


    Lurking

    whiteflags's Avatar


    Quote Originally Posted by Elysia
    View Post

    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. 10-16-2010


    #10

    Elysia is offline


    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.

    Quote Originally Posted by Adak
    View Post

    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.

    Quote Originally Posted by Salem
    View Post

    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.


  11. 10-17-2010


    #11

    brack is offline


    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…


  1. 2nd October 2015, 20:31


    #1

    This is my old system where my program compiles just fine:

    1. qt5-base 5.4.1-2

    2. qt5-declarative 5.4.1-2

    3. qt5-doc 5.4.1-2

    4. qt5-graphicaleffects 5.5.0-2

    5. qt5-location 5.4.1-2

    6. qt5-quick1 5.4.1-2

    7. qt5-quickcontrols 5.4.1-2

    8. qt5-script 5.4.1-2

    9. qt5-sensors 5.4.1-2

    10. qt5-svg 5.4.1-2

    11. qt5-tools 5.4.1-2

    12. qt5-translations 5.4.1-2

    13. qt5-webchannel 5.4.1-2

    14. qt5-webkit 5.4.1-2

    15. qt5-xmlpatterns 5.4.1-2

    16. qtchooser 48-1

    17. qtcreator 3.3.2-1

    To copy to clipboard, switch view to plain text mode 

    After the update:

    1. qt5-base 5.5.0-2

    2. qt5-declarative 5.5.0-2

    3. qt5-doc 5.5.0-2

    4. qt5-graphicaleffects 5.5.0-2

    5. qt5-location 5.5.0-2

    6. qt5-quick1 5.5.0-2

    7. qt5-quickcontrols 5.5.0-2

    8. qt5-script 5.5.0-2

    9. qt5-sensors 5.5.0-2

    10. qt5-svg 5.5.0-2

    11. qt5-tools 5.5.0-2

    12. qt5-translations 5.5.0-2

    13. qt5-webchannel 5.5.0-2

    14. qt5-webkit 5.5.0-2

    15. qt5-xmlpatterns 5.5.0-2

    16. qtchooser 48-1

    17. qtcreator 3.5.0-1

    To copy to clipboard, switch view to plain text mode 

    This is the error I get:

    1. 17:23:23: Running steps for project graphit...

    2. 17:23:23: Configuration unchanged, skipping qmake step.

    3. 17:23:23: Starting: "/usr/bin/make"

    4. 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

    5. In file included from /usr/include/qt/QtCore/qglobal.h:74:0,

    6. from /usr/include/qt/QtCore/qnamespace.h:37,

    7. from /usr/include/qt/QtCore/qobjectdefs.h:41,

    8. from /usr/include/qt/QtCore/qobject.h:40,

    9. from /usr/include/qt/QtCore/QObject:1,

    10. from src/controller.cpp:2:

    11. /usr/include/qt/QtCore/qurl.h:365:1: error: initializer provided for function

    12. Q_DECLARE_SHARED(QUrl)

    13. ^

    14. Makefile:975: recipe for target 'build/controller.o' failed

    15. make: *** [build/controller.o] Error 1

    16. 17:23:26: The process "/usr/bin/make" exited with code 2.

    17. Error while building/deploying project graphit (kit: Desktop)

    18. When executing step "Make"

    19. 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.


  2. 3rd October 2015, 04:27


    #2

    Default 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?


  3. 4th October 2015, 02:32


    #3

    Default Re: Program won’t compile since update from Qt5.4 to Qt5.5 | Error in Qt files?

    controller.cpp

    1. #include "controller.h"

    2. #include <QObject>

    3. #include <QString>

    4. #include <QVariant>

    5. #include <QVariantList>

    6. #include <QVariantMap>

    7. #include <string>

    8. #include <vector>

    9. #include "controller.h"

    10. #include "itemcontroller.h"

    11. #include "modelcontroller.h"

    12. #include "knowdesk/knowledgeDB.h"

    13. #include "templatecontroller.h"

    14. #include "filecontroller.h"

    15. #include "libs/easylogging++.h"

    16. void Controller::setQuery(QueryController* q) {

    17. query = q;

    18. }

    19. QueryController* Controller::getQuery() {

    20. return query;

    21. }

    22. .

    23. .

    24. .

    To copy to clipboard, switch view to plain text mode 

    controller.h

    1. #ifndef CONTROLLER_H

    2. #define CONTROLLER_H

    3. class QueryController;

    4. class FileController;

    5. class ModelController;

    6. class TemplateController;

    7. class ItemController;

    8. class KnowledgeDB;

    9. class Controller {

    10. public:

    11. void setQuery(QueryController*);

    12. QueryController* getQuery();

    13. void setFile(FileController*);

    14. FileController* getFile();

    15. void setModel(ModelController*);

    16. ModelController* getModel();

    17. void setTemplate(TemplateController*);

    18. TemplateController* getTemplate();

    19. void setItem(ItemController*);

    20. ItemController* getItem();

    21. void setDB(KnowledgeDB*);

    22. KnowledgeDB* getDB();

    23. private:

    24. QueryController* query;

    25. FileController* file;

    26. ModelController* model;

    27. TemplateController* template_;

    28. ItemController* item;

    29. KnowledgeDB* db;

    30. };

    31. #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:

    1. 02:25:07: Running steps for project graphit...

    2. 02:25:07: Configuration unchanged, skipping qmake step.

    3. 02:25:07: Starting: "/usr/bin/make"

    4. 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

    5. In file included from /usr/include/qt/QtCore/qglobal.h:74:0,

    6. from /usr/include/qt/QtCore/qnamespace.h:37,

    7. from /usr/include/qt/QtCore/qobjectdefs.h:41,

    8. from /usr/include/qt/QtCore/qobject.h:40,

    9. from /usr/include/qt/QtCore/QObject:1,

    10. from include/itemcontroller.h:4,

    11. from src/controller.cpp:6:

    12. /usr/include/qt/QtCore/qurl.h:365:1: error: initializer provided for function

    13. Q_DECLARE_SHARED(QUrl)

    14. ^

    15. Makefile:975: recipe for target 'build/controller.o' failed

    16. make: *** [build/controller.o] Error 1

    17. 02:25:09: The process "/usr/bin/make" exited with code 2.

    18. Error while building/deploying project graphit (kit: Desktop)

    19. When executing step "Make"

    20. 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

    1. QQmlEngine engine;

    To copy to clipboard, switch view to plain text mode 

    to

    1. QtQuickControlsApplication app(argc, argv);

    2. 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.


  4. 6th October 2015, 11:56


    #4

    Default 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» Что ему тут не нравится — ума не приложу. Все функции есть в хидере, ругаться стал недавно — ранее работал на ура. Перестраивала, перезапускала блокс(на всяк пожарный), а толку нет. Вот сам код:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "HW_C.h"
 
void less_1()
{
    bool flag=true;
    int temp;
    system("clear");
    while(flag)
    {
        printf("nВыберите задание:nt1 Среднее арифметическое двух чиселnt2 Перевод гривны в валютуnt3 Вывод текстаnt4 Квадрат числаnt5 Сумма и произведение трёхnt6 Назадn");
        scanf("%d", &temp);
        system("clear");
        switch(temp)
        {
            case 1: printf("Среднее арифметическое: %.3lfn",arithmetic_average()); break;
            case 2: exchange();break;
            case 3: text();break;
            case 4: printf("%dn", sqr()); break;
            case 5: summ_and_product_of_3();break;
            case 6: flag=false; break;
        }
    }
}

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



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

Вот та самая часть хидера:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <iomanip>
 
using namespace std;
 
 
void less_1();
void exchange();
void text();
int sqr();
void summ_and_product_of_3();
double arithmetic_average();
 
void less_2();
bool even_or_odd();
void summ_and_amount();



0



Модератор

Эксперт С++

12641 / 10135 / 6102

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

Сообщений: 27,170

29.12.2013, 11:03

6

У меня это все компилируется.
Возможно перепутали несколько одинаковых HW_C.h
В строчке
#include «HW_C.h»
щелкните правой кнопкой мыши по HW_C.h и выберите
Open HW_C.h (Открытие документа HW_C.h).



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’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugHW_Dop2.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugHW_Dop3.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugHW_Dop4.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugLess_1.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugLess_2.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugLess_3.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugLess_4.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugLess_5.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugLess_6.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugmain.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
||=== Build finished: 22 errors, 0 warnings (0 minutes, 4 seconds) ===|

И при чём здесь тогда:

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

компилятор почему-то ругается на 3 строку, говоря «expected initializer before void»

???

Добавлено через 1 минуту
И кто вас научил делать реализацию функции (insert_4_numb()) в заголовочном файле?

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

сама функция используется в 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

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

Хм.. Странно. У меня все выглядит немного по-другому.

Интересно было бы посмотреть.



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, с которой вам придется столкнуться не раз. Что же эта строчка означает, какие у неё причины появления, и главное – как быстро решить данную проблему?

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

Как несложно догадаться, компиляция – приведение кода на языке Си к виду машинного (двоичного) и преобразование множественных функций в простые операции, чтобы те смогли выполняться через встроенные операнды процессора. Выглядит всё достаточно просто, но сам процесс компиляции происходит значительно сложнее, и поэтому ошибка во время проведения оной может возникать по десяткам причин.

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

Мы узнали, к чему приводит данный процесс, давайте разберёмся, как он происходит:

  1. Первое, что делает компилятор – подгружает все инклуднутые файлы, а также меняет объявленные дефайны на значения, которое для них указано. Это необходимо затем, чтобы не нужно было по нескольку раз проходиться синтаксическим парсером в пределах одного кода. Также, в зависимости от среды, компилятор может подставлять функции на место их объявления или делать это уже после прохода синтаксическим парсером. В случае с С99, используется второй вариант реализации, но это и не столь важно.
  2. Далее он проверяет первичный синтаксис. Этот процесс проводится в изначальном компилируемом файле, и своеобразный парсер ищет, были ли описаны приведенные функции ранее, подключены ли необходимые библиотеки и прочее. Также проверяется правильность приведения типов данных к определенным значениям. Не стоит забывать, что в С99 используется строгая явная типизация, и вы не можете засунуть в строку, объявленную integer, какие-то буквенные значения. Если такое замечается, сразу вылетает ошибка.
  3. В зависимости от среды разработки, иногда предоставляется возможность последний раз протестировать код, который сейчас будет компилироваться, с запуском интерпретатора соответственно.
  4. Последним идет стек из различных действий приведения функций, базовых операнд и прочего к двоичному коду, что может занять какое-то время. Также вся структура файлов переносится в исполняемые 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?

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
  #include <iostream>
#include <string>

using namespace std;

string input;
int count = 0, length

void caesarCipher (string phrase)
{
    length = (int) phrase.length()
    
    for (count = 0; count < length; count++)
    {
       if (isalpha(phrase[count])) 
       {
           phrase[count] = tolower(phrase[count]);
           for (i = 0; i < 13; i++)
           {
              if (phrase[count] == 'z') 
                  phrase[count] = 'a';
              else
                  phrase[count]++;
           }
       }
    }
    cout << "Results: " << phrase << endl;
}

int main() 
{   
    cout << "Enter your phrase: ";
    cin >> input;
    
    caesarCipher(input);
    return 0;
}

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:

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
#include <iostream>
#include <string>

using namespace std;  // avoid this

string input;
int count = 0, length

void caesarCipher (std::string& phrase);

int main() 
{   

std::string input;


    std::cout << "Enter your phrase: ";
   std:: cin >> input;
    
    caesarCipher(input);
    return 0;
}

void caesarCipher (const string& phrase)
{
   std::size_t length = (int) phrase.length()

std::string OutputPhrase;
    
    for (std::size_t count = 0; count < length; count++)
    {
       if (isalpha(phrase[count])) 
       {
           OutputPhrase[count] = tolower(phrase[count]);
           for (i = 0; i < 13; i++)
           {
              if (phrase[count] == 'z') 
                  OutputPhrase[count] = 'a';
              else
                  OutputPhrase[count]++;
           }
       }
    }
    cout << "Results: " << OutputPhrase << endl;
}

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

Viphuchit Sirikhemaporn's user avatar

1

You add the semicolon that is missing at the end of long unsigned int t

answered Aug 26, 2015 at 10:47

Majenko's user avatar

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

evolutionizer's user avatar

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

Nick GammonNick 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.

Понравилась статья? Поделить с друзьями:
  • Error initializer expression list treated as compound expression in initializer
  • Error initializer element is not a compile time constant
  • Error initialized or created transport for authentication
  • Error initialize specified but the data directory has files in it aborting
  • Error initialize scatter file failed