Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit declaration of scandir; alphasort is undeclared

Tags:

c

c99

scandir

I am trying to use scandir to print a list of files in the current directory. When I try to compile, I am receiving the following errors and warnings:

warning: implicit declaration of function ‘scandir’ [-Wimplicit-function-declaration]
error: ‘alphasort’ undeclared (first use in this function)
note: each undeclared identifier is reported only once for each function it appears in

I am including <dirent.h>, which to my knowledge should define scandir() and all related functions. And I don't see any errors in my code:

#include <dirent.h>
...
int printFiles(){
    struct dirent **nameList;
    int numOfFiles = scandir(".", &nameList, 0, alphasort);

    //TODO print file names
    return numOfFiles;
}
....

I am running Ubuntu 12.04, and I'm compiling using gcc with the -c99 flag.

Am I simply overlooking something? I can't figure out why it's failing to compile.

like image 657
Bluedanes Avatar asked Oct 25 '25 23:10

Bluedanes


1 Answers

If you use -std=c99, only functions that are strictly a part of the C99 standard are included by the header files. scandir() is not in the C99 standard. Therefore, you have to set a preprocessor variable to ensure that the function prototype is included. For example, the man page for scandir() indicates that setting the _BSD_SOURCE or _SVID_SOURCE preprocessor variables before you do the #include will fix the problem. Or, you can use #define _GNU_SOURCE which will in turn set quite a few different variables for you (including _BSD_SOURCE and _SVID_SOURCE).

Your code will still compile with the warning and work because C allows you to compile with implicitly defined functions, and the linker will correctly link the call to scandir() to the proper function.

like image 119
ScottKu Avatar answered Oct 28 '25 14:10

ScottKu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!