2016-10-10 57 views
-1

我一直在瘋狂地試圖讓下面的代碼工作。預處理器定義WIDR和LIDR都沒有工作,它給我的編譯錯誤:預處理器定義在C中不起作用

projects/elcain.c: In function ‘main’: 
projects/elcain.c:17:6: error: ‘WIDR’ undeclared (first use in this function) 
if (WIDR) { 
    ^
projects/elcain.c:17:6: note: each undeclared identifier is reported only once for each function it appears in 
projects/elcain.c:19:13: error: ‘LIDR’ undeclared (first use in this function) 
} else if (LIDR) { 

我真的沒有用預處理宏,或在一般的預處理器的經驗,這樣下去容易在我身上。

下面的代碼:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

#ifdef _WIN32 
#define WIDR 1 
#elif defined _linux_ 
#define LIDR 1 
#endif 

int main() { 

char* directory = (char*) malloc (1); 
if (WIDR) { 
    strcpy(directory, "C:\\TEMP\\"); 
} else if (LIDR) { 
    strcpy(directory, "~/.temp/"); 
} else { 
    *directory = 0x00; 
} 

printf("%s\n", directory); 
return 0; 
} 
+0

無論'_WIN32'也不'_linux_'定義。 – tkausl

+2

如果沒有定義'_WIN32',那麼'WIDR'也沒有定義。 Anywa,這是完全錯誤的,因爲'WIRD'和'LIDR'不能同時定義,但它們都在程序中使用。 –

+0

順便說一句'(char *)malloc(1);'是荒謬的。想想看。 –

回答

1

你所尋找的是這樣的:

#include <stdlib.h> 

#if defined unix  ||              \ 
    defined __unix  ||              \ 
    defined __unix__ ||              \ 
    defined __linux__ ||              \ 
    defined __FreeBSD__ ||              \ 
    defined __CYGWIN__ ||              \ 
    (defined __APPLE__ && defined __MACH__) 
    static const char TMP_DIR[] = "~/.temp/"; 
#elif defined WIN32 ||              \ 
     defined _WIN32 ||              \ 
     defined __WIN32 
    static const char TMP_DIR[] = "C:\\TEMP\\"; 
#else 
    #error "Platform not supported" 
#endif 

int 
main(void) 
{ 
    printf("%s\n", TMP_DIR); 
    return EXIT_SUCCESS; 
} 
+1

其他方法,是嗎?如果定義了windows - >'「C:\\ TEMP \\」'。 – Lundin

+0

我的不好,是的,'有點匆忙:) –

3

你可能只是想這樣的:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 


int main() { 
#ifdef _WIN32 
    char directory[] = "C:\\TEMP\\"; 
#elif defined _linux_ 
    char directory[] = "~/.temp/"; 
#else 
#error Neither _WIN32 nor _linux_ are defined 
#endif 

    printf("%s\n", directory); 
    return 0; 
} 
+1

我認爲你的條件中的第三種情況應該是'#else'而不是'#elif'! –

+0

感謝您的幫助!在嘗試像這樣的東西之前,會考慮更多的C。再次感謝! –

0

其實都WIDR和LIDR是條件編譯指令。換句話說,它們僅在編譯時存在。

更改您這樣的代碼:

#ifdef WIDR 
    strcpy(directory, "C:\\TEMP\\"); 
#elif defined LDIR 
    strcpy(directory, "~/.temp/"); 
#else 
    *directory = 0x00; 
#endif 

那麼編譯錯誤將消失