参考资料: https://msdn.microsoft.com/en-us/library/d9x1s805.aspx
1. data_seg
#pragma data_seg(".test")
int g_test1 = 5;
int g_test2 = 5;
#pragma data_seg()
#pragma comment(linker, "/SECTION:.test,RW")
int g_another = 5;
结果: g_test1 和 g_test2 被分配到 .test 段中, g_another 被分配到默认的 .data 段中
2. section
#pragma section(".test", read, write)
__declspec(allocate(".test")) int g_test1 = 5;
#pragma section(".test", read, write)
__declspec(allocate(".test")) int g_test2 = 8;
int g_another = 5;
另外如果希望在程序中可以修改const变量, 则必须把const变量分配到可读写的自定义段中, 而不是默认的只读数据段中!
具体方法如下:
#pragma section(".handler", read, write)
__declspec(allocate(".test")) const int g_test = 8;
或者
#pragma data_seg(".data")
__declspec(allocate(".data")) const QtMsgHandler g_pOldHandler = NULL;
#pragma data_seg()
修改const变量
int* pInt = const_cast<int*>(&g_test);
qDebug() << "pInt = " << *pInt;
*pInt = 6;
qDebug() << "pInt = " << *pInt;