test.cpp文件内容如下:
char g_szTest[100] = "original";
现在, 我要在main.cpp中引用这个数组怎么办呢? 肯定不能把char g_szTest[100] = "original";放到test.h文件中, 然后用main.cpp来包含test.h啊, 这样容易形成编译碰撞, 也是应该禁止的。 那怎么办? 其实, 我们可以在main.cpp中这样搞:
#include <iostream>
using namespace std;
extern char g_szTest[];
int main()
{
cout << g_szTest << endl;
return 0;
}
这样就有结果了。
现在的问题是, 如果要在main.cpp中修改g_szTest数组, 那该怎么办呢? 看看如下代码:
#include <iostream>
using namespace std;
extern char g_szTest[];
int main()
{
cout << g_szTest << endl;
int size = sizeof(g_szTest); // error
strncpy(g_szTest, "hello world", size - 1);
g_szTest[size - 1] = '\0';
return 0;
}
原来, 在main.cpp中, 无法直接获取到g_szTest的size啊, 那怎么办呢? 凉拌, 不要在main.cpp中直接改变g_szTest中的串, 而是由test.cpp来直接提供改变g_szTest中串的接口, 这样才合理啊, 如下:
test.cpp中的内容为:
#include <iostream>
char g_szTest[100] = "original";
void setValue(const char *pValue)
{
// 空指针, 我就不判断了, 程序住主要用作示意
int size = sizeof(g_szTest);
strncpy(g_szTest, pValue, size - 1);
g_szTest[size - 1] = '\0';
}
test.h中的内容为:
void setValue(const char *pValue);
main.cpp中的内容为:
#include "test.h"
#include <iostream>
using namespace std;
extern char g_szTest[];
int main()
{
cout << g_szTest << endl; // original
setValue("good");
cout << g_szTest << endl; // good
return 0;
}
好了, main.cpp要想修改test.cpp中的变量, 那还是通过test.cpp对外提供的接口来修改吧, 模块间的消息通知不经常就是通过调用来实现么?