再谈全局数组的外引用

        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对外提供的接口来修改吧, 模块间的消息通知不经常就是通过调用来实现么?

 


 

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值