2017-04-12 145 views
0

我在c中測試execvpe(),我嘗試了下面的代碼,它導致錯誤,因爲「隱式聲明函數'execvpe'在C99 [-Wimplicit-function-declaration]中無效」 。execvpe隱式聲明錯誤

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#define _GNU_SOURCE 
#include <unistd.h> 

int main(int argc, char const *argv[]) 
{ 
    //execl("/bin/echo", "echo", "Hello, world", NULL); 
    char *path = getenv("PATH"); 
    char pathenv[strlen(path) + sizeof("PATH=")]; 
    sprintf(pathenv, "PATH=%s", path); 
    char *envp[] = {pathenv, NULL}; 
    char *tests[] = {"ls", "-lR", NULL}; 
    execvpe(tests[0], tests, envp); 
    fprintf(stderr, "failed to execute \"%s\"\n", tests[0]); 
    return 0; 
} 

然後我如下測試此代碼測試現存的狀態(這是我從Compiler warnings for execvpe function複製,這一次沒有錯誤。是否有任何人可以幫助我弄清楚什麼是錯在我上面的代碼?謝謝!

#include <unistd.h> 
extern int execvpe(const char *file, char *const argv[], char *const envp[]); 

回答

0
之前任何 #include指令

移動#define _GNU_SOURCE指令,例如

#define _GNU_SOURCE 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 

glibc中,所有這些頭拉入features.h,它根據_XOPEN_SOURCE,_POSIX_SOURCE,_GNU_SOURCE等的設置設置各種宏。在第一次包括時,它沒有被設置。當你開始使用unistd.h時,features.h已經包含在內,並且不會再應用。

+0

非常感謝!在我移動它後,它有錯誤,如「錯誤:函數的隱式聲明'execvpe'在C99中是無效的[-Werror,-Wimplicit-function- declaration] execvpe(tests [0],tests,envp);」 – coco

+0

@coco它在這裏與GCC 6.3.1和Glibc 2.25一起工作。你是否可能使用其他一些不提供'execvpe'的C標準庫? – ephemient

+0

你可以在這裏看到缺少警告的演示:https://godbolt.org/g/m2eyRi – ephemient