2014-12-05 72 views
0

在我的代碼中我有一個extern變量(test.h) - extern int tmp; - 聲明,我也有兩個實現文件,用於linux:test_linux.ctest_windows.c。在那裏,我有一個定義(int tmp = 0;),均在test_linux.ctest_windows.c之間。當然,我在這兩個文件檢查:#ifdef __WIN__ ......和#ifdef __LIN__ ...在2個文件(linux/windows)版本之間使用extern變量

當我試圖在Linux上的gcc來編譯它,它在某種程度上「」看到'無論是在test_linux.ctest_windows.c聲明的變量,但是:

  1. 在Linux上,GCC應該看到的聲明只能從test_linux.c
  2. 和窗戶,視覺應該只看到自定義test_windows.c

是否有可能實現這樣的目標?

test.h文件:

#ifndef _TEST_H_ 
#define _TEST_H_ 

#ifdef __cplusplus 
extern "C" { 
#endif 

void use_temp(); 

extern volatile int temp = 0; 

#ifdef __cplusplus 
} 
#endif 
#endif 

test_linux.c文件:

#include "test.h" 

#if ((defined(__linux__) || defined(__gnu_linux) || defined(__linux)) && defined(__GNUC__)) 
#include <unistd.h> 
#include <sys/time.h> 
#include <sys/resource.h> 

int temp = 0; 

#endif 

void use_temp() 
{ 
    temp = 1024; 
} 

test_windows.c文件:

#include "test.h" 

#if defined(_WIN32) || defined(_WIN64) 
#include <windows.h> 
#include <winbase.h> 
#elif ((defined(_WIN32) || defined(_WIN64)) && (defined(_MSC_VER))) 
#include <windows.h> 
#include <winbase.h> 
#include <intrin.h> 
#include <stdint.h> 

int temp = 0; 

#endif 


void use_temp() 
{ 
    temp = 1024; 
} 

和錯誤:

$ gcc -g -c test_windows.c test_linux.c main.c 
In file included from test_windows.c:1:0: 
test.h:10:21: warning: ‘temp’ initialized and declared ‘extern’ [enabled by default] 
extern volatile int temp = 0; 
        ^
In file included from test_linux.c:1:0: 
test.h:10:21: warning: ‘temp’ initialized and declared ‘extern’ [enabled by default] 
extern volatile int temp = 0; 
        ^
test_linux.c:8:5: error: conflicting type qualifiers for ‘temp’ 
int temp = 0; 
    ^
In file included from test_linux.c:1:0: 
test.h:10:21: note: previous definition of ‘temp’ was here 
extern volatile int temp = 0; 
        ^
In file included from main.c:1:0: 
test.h:10:21: warning: ‘temp’ initialized and declared ‘extern’ [enabled by default] 
extern volatile int temp = 0; 
+0

您應該依賴現有的定義而不是創建您的擁有者。更好的是,您可以使用像CMake這樣的工具根據運行的平臺排除或包含特定的文件。 – Chnossos 2014-12-05 13:57:10

+0

@Chnossos:我該怎麼做這樣的事情?我在哪裏可以讀到它?我甚至不知道在google中輸入什麼,有什麼建議? :) – yak 2014-12-05 20:36:15

回答

0

你想要的是完全可以實現的,你需要找到編譯錯誤的原因。

對於初學者來說,在一個文件的開頭,例如:

#if defined(__WIN__) && defined(__LIN__) 
#error Only one OS should be defined 
#endif 

這將保護你不受任何現有和將來的錯誤添加檢查。

+0

好吧,這是我的'test.h'文件:http://pastie.org/private/olnpdjylpvxvcx4azrdnxg,'test_linux.c'文件:http://pastie.org/private/z6kgfzrbx2xvnco4yth0ea和'test_windows.c '文件:http://pastie.org/private/wonzb8ubjpl0jnugs4tw和錯誤:'錯誤:'temp''的衝突類型限定符 – yak 2014-12-05 20:38:13