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

Arduino Forum

Loading

Я пытаюсь перенести библиотеку 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

  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…


Я пытаюсь перенести библиотеку 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, а исходная версия содержит [email protected]. Например:

@$(COMPILE) -M -MF $(subst .o,.d.tmp,$@) -MT $@ -E $(C_FLAGS) [email protected] $< -o [email protected]

и я изменил [email protected] за @[email protected]потому что я видел, что в более старом проекте они так и поступали. Однако, если я оставлю как[email protected] Я просто получаю:

SomeFile.c:1:1 fatal error: OneHeader.h: No such file or directory

Я начинаю думать, что мой Makefile где-то не так…

Я неправильно понял параметр компилятора… Несколькими строками выше мой make-файл создает @.viaфайлы, передающие DEFINES и INCLUDES

       @echo $(patsubst %, '%', $(C_DEFINES)) > [email protected]
       @echo $(C_INCLUDE) >> [email protected]

и те @.viaфайлы передаются в качестве дополнительных аргументов для компиляции. Хотя дляarmcc в --viaподдерживается см. здесь, я обнаружил, что для g++ — согласно документу gcc — синтаксис@<your_file>. Итак, что@[email protected] просто анализирует [email protected] к <your_file>.via.

Теперь я все еще получаю initializer provided for function сообщение об ошибке.

ОБНОВЛЕНИЕ 2:

Я нашел проблему и объяснил, что произошло, в разделе ответов. Смотри ниже.

BalexD

0 / 0 / 0

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

Сообщений: 16

1

28.12.2013, 21:41. Показов 31396. Ответов 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



Модератор

Эксперт С++

13245 / 10387 / 6210

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

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

28.12.2013, 21:48

2

Что-то не так в HW_C.h
Что там написано?



0



Эксперт С++

1673 / 1045 / 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



Модератор

Эксперт С++

13245 / 10387 / 6210

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

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

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



5496 / 4891 / 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



5496 / 4891 / 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_mainHW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_C.h|73|first defined here|
objDebugHW_Dop2.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_C.h|73|first defined here|
objDebugHW_Dop3.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_C.h|73|first defined here|
objDebugHW_Dop4.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_C.h|73|first defined here|
objDebugLess_1.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_C.h|73|first defined here|
objDebugLess_2.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_C.h|73|first defined here|
objDebugLess_3.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_C.h|73|first defined here|
objDebugLess_4.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_C.h|73|first defined here|
objDebugLess_5.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_C.h|73|first defined here|
objDebugLess_6.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_C.h|73|first defined here|
objDebugmain.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_mainHW_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



5496 / 4891 / 831

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

Сообщений: 13,587

10.01.2014, 00:07

12

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

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

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



0



  1. 2nd October 2015, 19: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, 03: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, 01: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, 10: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.


  1. Я пишу пустой код, безо всего, выделяет слово void и выдаёт такую ошибку:

    Arduino: 1.6.8 (Windows 7), Плата:»Arduino/Genuino Uno»

    sketch_may03a:7: error: expected initializer before ‘void’

    E:СашаАрдуйноsketch_may03asketch_may03a.ino: In function ‘void setup()’:

    sketch_may03a:5: error: expected ‘;’ before ‘}’ token

    E:СашаАрдуйноsketch_may03asketch_may03a.ino: In function ‘void loop()’:

    sketch_may03a:10: error: expected ‘;’ before ‘}’ token

    exit status 1
    expected initializer before ‘void’

    Что делать? Скачал программу с официального сайта.

  2. внимательно читать сообщение об ошибке: в функции setup() в строках 5 и 10 отсутствует символ «;» в конце строки.

  3. кто может помочь в этом??

    Вложения:

    • 2016-05-03 (1).png

  4. Не определен объект Audio. Скорее всего отсутствует библиотека или она не включена в программу.

  5. Arduino: 1.6.8 Hourly Build 2016/01/27 03:44 (Windows 10), Плата:»Arduino/Genuino Uno»

    sketch_oct31a:53: error: expected unqualified-id before ‘{‘ token

    sketch_oct31a:61: error: expected declaration before ‘}’ token

    exit status 1
    expected unqualified-id before ‘{‘ token

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

    Помогите! Обьясните что делать?

  6. C:UsersUserDesktoparduino-nightlyhardwarearduinoavrcoresarduino/main.cpp:43: undefined reference to `setup’

    collect2.exe: error: ld returned 1 exit status

    exit status 1
    Ошибка компиляции для платы Arduino/Genuino Uno.
    Что за ошибка?

Решено: Ошибка компиляции при перезагрузке оператора

Модератор: Модераторы разделов

Аватара пользователя

kt315e

Сообщения: 315
ОС: Debian 11

Решено: Ошибка компиляции при перезагрузке оператора

При компиляции кода (кусочек примера из Эккеля Философия С++ т1 )
возникает ошибка » expected initializer before ‘operator’ » в выделеной жирным строке.

Код:

class Integer
{
long i;
Integer* This() {return this;}
Integer (long ll = 0) : i(ll) {}
friend const Integer operator-(const Integer& a);
}
const Integer operator-(const Integer& a)
{
return Integer(-a.i);
}

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

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

  • Яндекс еда ошибка привязки карты
  • Indesit witl 106 ошибка f08
  • Initializer element is not constant ошибка
  • Indesit wite 1077 ошибка н20
  • Initializecomponent c ошибка

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

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