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:\Users\cs091770\Desktop\version.cpp invalid conversion from `const char*’ to `char’

    In printAll function there is this error…

    22 C:\Users\cs091770\Desktop\version.cpp expected `;’ before string constant
    23 C:\Users\cs091770\Desktop\version.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 Settings\Owner\My Documents\foo\foo.cpp:16: error: initializer provided for function
    C:\Documents and Settings\Owner\My Documents\foo\foo.cpp:18: error: expected constructor, destructor, or type conversion before ‘=’ token
    C:\Documents and Settings\Owner\My Documents\foo\foo.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 Settings\Owner\My Documents\foo\foo.cpp: In member function ‘int Data::init()’:
    C:\Documents and Settings\Owner\My Documents\foo\foo.cpp:18: error: invalid conversion from ‘const char*’ to ‘char’
    C:\Documents and Settings\Owner\My Documents\foo\foo.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:

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

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

Интересное по теме:

  • Inst 08104 04 ошибка ман тга
  • Initializer element is not constant ошибка
  • Initializeenginegraphics failed ошибка раст
  • Inst 08103 04 ошибка ман
  • Initializecomponent c ошибка

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: