在 Debian 上 编译使用 opendir() 的程序 其实很简单,opendir() 是 POSIX 标准函数,声明在 <dirent.h> 里,不需要额外安装特殊库,只要使用正确的头文件和链接方式即可。
下面一步一步说明。
opendir.c:
#include <stdio.h>
#include <dirent.h>
int main(void) {
DIR *dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
gcc opendir.c -o opendir
或(等价):
cc opendir.c -o opendir
注意:
opendir()属于libc,不需要-ldl、-lpthread等特殊库
opendirwarning: implicit declaration of function ‘opendir’
✅ 原因:
没加头文件
✅ 解决:
#include <dirent.h>
DIR 未定义unknown type name ‘DIR’
✅ 原因:
同样是没有 <dirent.h>
如果是 .cpp 文件:
#include <dirent.h>
编译:
g++ opendir.cpp -o opendir
gcc --version
如果没有:
sudo apt update
sudo apt install build-essential
sudo apt install build-essential
nano opendir.c
gcc opendir.c -o opendir
./opendir
可以告诉我:
cat /etc/os-release)我可以给你更精确的编译方式。