Ошибка implicit declaration of function

My compiler (GCC) is giving me the warning:

warning: implicit declaration of function

Why is it coming?

Peter Mortensen's user avatar

asked Dec 9, 2011 at 3:49

Angus's user avatar

2

You are using a function for which the compiler has not seen a declaration («prototype«) yet.

For example:

int main()
{
    fun(2, "21"); /* The compiler has not seen the declaration. */       
    return 0;
}

int fun(int x, char *p)
{
    /* ... */
}

You need to declare your function before main, like this, either directly or in a header:

int fun(int x, char *p);

answered Dec 9, 2011 at 3:50

cnicutar's user avatar

cnicutarcnicutar

177k25 gold badges364 silver badges391 bronze badges

15

The right way is to declare function prototype in header.

Example

main.h

#ifndef MAIN_H
#define MAIN_H

int some_main(const char *name);

#endif

main.c

#include "main.h"

int main()
{
    some_main("Hello, Worldn");
}

int some_main(const char *name)
{
    printf("%s", name);
}

Alternative with one file (main.c)

static int some_main(const char *name);

int some_main(const char *name)
{
    // do something
}

VLL's user avatar

VLL

9,5111 gold badge28 silver badges54 bronze badges

answered Dec 3, 2014 at 14:26

Faizal Pribadi's user avatar

When you do your #includes in main.c, put the #include reference to the file that contains the referenced function at the top of the include list.
e.g. Say this is main.c and your referenced function is in «SSD1306_LCD.h»

#include "SSD1306_LCD.h"    
#include "system.h"        #include <stdio.h>
#include <stdlib.h>
#include <xc.h>
#include <string.h>
#include <math.h>
#include <libpic30.h>       // http://microchip.wikidot.com/faq:74
#include <stdint.h>
#include <stdbool.h>
#include "GenericTypeDefs.h"  // This has the 'BYTE' type definition

The above will not generate the «implicit declaration of function» error, but below will-

#include "system.h"        
#include <stdio.h>
#include <stdlib.h>
#include <xc.h>
#include <string.h>
#include <math.h>
#include <libpic30.h>       // http://microchip.wikidot.com/faq:74
#include <stdint.h>
#include <stdbool.h>
#include "GenericTypeDefs.h"     // This has the 'BYTE' type definition
#include "SSD1306_LCD.h"    

Exactly the same #include list, just different order.

Well, it did for me.

answered Nov 9, 2016 at 12:04

tomc's user avatar

tomctomc

1111 silver badge2 bronze badges

0

You need to declare the desired function before your main function:

#include <stdio.h>
int yourfunc(void);

int main(void) {

   yourfunc();
 }

answered Feb 8, 2020 at 12:48

Poussy's user avatar

When you get the error: implicit declaration of function it should also list the offending function. Often this error happens because of a forgotten or missing header file, so at the shell prompt you can type man 2 functionname and look at the SYNOPSIS section at the top, as this section will list any header files that need to be included. Or try http://linux.die.net/man/ This is the online man pages they are hyperlinked and easy to search.
Functions are often defined in the header files, including any required header files is often the answer. Like cnicutar said,

You are using a function for which the compiler has not seen a
declaration («prototype») yet.

answered Nov 26, 2015 at 7:59

Sal's user avatar

If you have the correct headers defined & are using a non GlibC library (such as Musl C) gcc will also throw error: implicit declaration of function when GNU extensions such as malloc_trim are encountered.

The solution is to wrap the extension & the header:

#if defined (__GLIBC__)
  malloc_trim(0);
#endif

answered Aug 28, 2015 at 23:05

Stuart Cardall's user avatar

2

This error occurs because you are trying to use a function that the compiler does not understand. If the function you are trying to use is predefined in C language, just include a header file associated with the implicit function.
If it’s not a predefined function then it’s always a good practice to declare the function before the main function.

answered Aug 2, 2021 at 11:31

Ndaruga's user avatar

Don’t forget, if any functions are called in your function, their prototypes must be situated above your function in the code. Otherwise, the compiler might not find them before it attempts to compile your function. This will generate the error in question.

Peter Mortensen's user avatar

answered Dec 15, 2020 at 9:23

Chris's user avatar

ChrisChris

192 bronze badges

1

The GNU C compiler is telling you that it can find that particular function name in the program scope. Try defining it as a private prototype function in your header file, and then import it into your main file.

Peter Mortensen's user avatar

answered Jul 26, 2022 at 22:19

Gabriel soft's user avatar

1

До стандарта c99 разрешалось использовать (вызывать) функции без явного предварительного их объявления. В таким случае, наличие вызова подобной функции f() в коде воспринималось компилятором так же, как если бы ранее точки использования было бы объявление вида:

int f();

Т.е. предполагается функция, возвращающая int и принимающая ещё неизвестное, но фиксированное кол-во аргументов. И, например, такой код:

int main(void) {
    f(1, 2);
    return 0;
}

int f(int a, int b) { return 0; }

является вполне валидным для c89. Но в c99 эту лавочку прикрыли, и следующие строгим стандартам компиляторы должны подобный код запрещать. Однако для совместимости часто ограничиваются предупреждениями (в Вашем случае как раз предупреждение, а не ошибка). Для исключения таких проблем нужно добавить предварительное объявление функции перед её вызовом (или просто перенести всё реализацию выше).

Problem:

While trying to compile your C/C++ program, you see an error message like

../src/main.c:48:9: error: implicit declaration of function 'StartBenchmark' [-Werror=implicit-function-declaration]
         StartBenchmark();

Solution:

implicit declaration of function means that you are trying to use a function that has not been declared. In our example above, StartBenchmark is the function that is implicitly declared.

This is how you call a function:

StartBenchmark();

This is how you declare a function:

void StartBenchmark();

The following bullet points list the most common reasons and how to fix them:

  1. Missing #include: Check if the header file that contains the declaration of the function is #included in each file where you call the function (especially the file that is listed in the error message), before the first call of the function (typically at the top of the file). Header files can be included via other headers,
  2. Function name typo: Often the function name of the declaration does not exactly match the function name that is being called. For example, startBenchmark() is declared while StartBenchmark() is being called. I recommend to fix this by copy-&-pasting the function name from the declaration to wherever you call it.
  3. Bad include guard: The include guard that is auto-generated by IDEs often looks like this:
    #ifndef _EXAMPLE_FILE_NAME_H
    #define _EXAMPLE_FILE_NAME_H
    // ...
    #endif

    Note that the include guard definition _EXAMPLE_FILE_NAME_H is not specific to the header filename that we are using (for example Benchmark.h). Just the first of all header file names wil

  4. Change the order of the #include statements: While this might seem like a bad hack, it often works just fine. Just move the #include statements of the header file containing the declaration to the top. For example, before the move:
    #include "Benchmark.h"
    #include "other_header.h"

    after the move:

    #include "Benchmark.h"
    #include "other_header.h"

Здравствуйте.

Имеется файл kmain.c, в нём у нас входная точка и главная функция, которая использует функцию initVGAMemory();, прототип функции описан в заголовочном файле vgamemory.h(реализация в vgamemory.c).

К kmain.c подключён лишь один заголовочный файл kernel.h, в нём vgamemory.h никаким образом не подключается, получается, в kmain.c мы никаким образом не можем использовать эту функцию, т.к. она напрямую и косвенно не подключена.

При компиляции вылезает предупреждение:

./source/kmain.c:7:5: warning: implicit declaration of function ‘initVGAMemory’ [-Wimplicit-function-declaration]

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

implicit declaration of function

The implicit declaration of function error is very common in C language. Either you are a beginner in C or moved to C from a high-level language. C is procedural programming language. So it is very important to declare every function before using. The flow control works on Top-Down basis.

int main()
{
    callit(1, "12"); /* Declare that function before using it */
    return 0;
}

int callit(int x, char *p)
{
    /* Some Code */
}

The actual error message is

warning: implicit declaration of function

What causing Implicit declaration of function error in C?

This error will generally show the name of the function in the compiler. You are using the function without declaring it. A more in-depth solution Implicit declaration of function in C is available here.

1) If you are using pre-defined function then it is very likely that you haven’t included the header file related to that function. Include the header file in which that function is defined.

#include &amp;amp;lt;unistd.h&amp;amp;gt;

2) If you are using any custom function then it is a good practice to declare the function before main. Sometimes the problem comes due to the return type of the function. By default, C language assumes the return type of any function as ‘int’. So, declare the function before main, that will definitely resolve that issue.

int callit(int x, char *p); /* Declare it in this way before main */

Final Words

If you are still getting any problem, then feel free to comment down your code.

Понравилась статья? Поделить с друзьями:
  • Ошибка http status code 400 ps3 hen
  • Ошибка ins 0104 мерседес актрос
  • Ошибка imovie 10004
  • Ошибка hyundai p20ee00
  • Ошибка http status 400 bad request