如何实现定义一个全局变量并且再多个obj中被引用而不报错,有修改意见吗
LNK2005 "struct Context ctx" (?ctx@@3U_Context@@A) already defined in a.obj proj X:\proj\b.obj 1
x.h
#pragma once
extern struct Context ctx;
a.h
#pragma once
#include "x.h"
a.cpp
#include "a.h"
ctx.do_some_handles();
b.h
#pragma once
#include "x.h"
b.cpp
#include "b.h"
ctx.do_some_other_handles();
通常做法是在头文件中声明, 在某个源文件中定义, 这样在所有的源文件中都是公用的。
在a.cpp或者b.cpp 中定义ctx变量。或者在a和b都定义应该也可以。
struct Context ctx;