在我的代碼中我有一個extern變量(test.h) - extern int tmp;
- 聲明,我也有兩個實現文件,用於linux:test_linux.c
和test_windows.c
。在那裏,我有一個定義(int tmp = 0;
),均在test_linux.c
和test_windows.c
之間。當然,我在這兩個文件檢查:#ifdef __WIN__
......和#ifdef __LIN__
...在2個文件(linux/windows)版本之間使用extern變量
當我試圖在Linux上的gcc來編譯它,它在某種程度上「」看到'無論是在test_linux.c
和test_windows.c
聲明的變量,但是:
- 在Linux上,GCC應該看到的聲明只能從
test_linux.c
, - 和窗戶,視覺應該只看到自定義
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;
您應該依賴現有的定義而不是創建您的擁有者。更好的是,您可以使用像CMake這樣的工具根據運行的平臺排除或包含特定的文件。 – Chnossos 2014-12-05 13:57:10
@Chnossos:我該怎麼做這樣的事情?我在哪裏可以讀到它?我甚至不知道在google中輸入什麼,有什麼建議? :) – yak 2014-12-05 20:36:15