2016-10-10 7 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

BTW '(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

他の方法で、ええ?もし定義されたウィンドウ - > '' 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

あなたの条件の3番目のケースは#elifの代わりに '#else'であるべきだと思います! –

+0

助けてくれてありがとう!このようなものを試す前に、もっとCを調べます。再度、感謝します! –

0

両方のWiDrをし、 LIDRは条件付きコンパイル指令です。つまり、コンパイル時にのみ存在します。

は、このようにコードを変更し

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

その後、コンパイルエラーが