C 在两个文件(linux/windows)版本之间使用extern变量
在我的代码中,我有一个extern变量(test.h)-C 在两个文件(linux/windows)版本之间使用extern变量,c,extern,C,Extern,在我的代码中,我有一个extern变量(test.h)-extern inttmp-声明,我还有两个linux实现文件:test\u linux.c和test\u windows.c。在那里,我有一个定义(inttmp=0;),在test\u linux.c和test\u windows.c中都有。当然,我在两个文件中都进行了检查:#ifdef uuu-WIN uu。。。和#ifdef_uuulin_uu 当我尝试在linux上用gcc编译它时,它不知何故“看到”了test_linux.c和te
extern inttmp代码>-声明,我还有两个linux实现文件:test\u linux.c
和test\u windows.c
。在那里,我有一个定义(inttmp=0;
),在test\u linux.c
和test\u windows.c
中都有。当然,我在两个文件中都进行了检查:#ifdef uuu-WIN uu
。。。和#ifdef_uuulin_uu
当我尝试在linux上用gcc编译它时,它不知何故“看到”了test_linux.c
和test_windows.c
中声明的变量,但是:
在linux上,gcc应该只看到test\u linux.c
中的声明
在windows上,visual应该只查看test\u 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
#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_linux.c
文件:
#ifndef _TEST_H_
#define _TEST_H_
#ifdef __cplusplus
extern "C" {
#endif
void use_temp();
extern volatile int temp = 0;
#ifdef __cplusplus
}
#endif
#endif
#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;
}
和错误:
$ 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;
您想要的是完全可以实现的,您需要找到编译错误的原因
对于初学者,请在其中一个文件的开头添加检查,例如:
#if defined(__WIN__) && defined(__LIN__)
#error Only one OS should be defined
#endif
这将保护您免受当前和将来的任何错误。您应该依赖现有的定义,而不是创建自己的定义。更好的方法是,您可以使用诸如CMake之类的工具来排除或包含特定的文件,具体取决于它运行的平台。@Chnossos:我如何才能做到这一点?我在哪里可以读到它?我甚至不知道在谷歌上输入什么,有什么建议吗?:)好的,这是我的test.h
文件:,test\u linux.c
文件:,和test\u windows.c
文件:以及错误:error:temp'的类型限定符冲突