预处理器定义不适用于C语言

时间:2016-10-10 13:09:11

标签: c c-preprocessor

我一直疯狂地试图让以下代码运行起来。预处理器定义WIDR和LIDR不起作用,它给我编译错误:

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;
}

3 个答案:

答案 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 :(得分:2)

您正在寻找的是这样的:

#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;
}

答案 2 :(得分:0)

实际上,WIDR和LIDR都是条件编译指令。换句话说,它们仅在编译时存在。

更改您的代码:

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

然后编译错误将消失