GCC:调用静态对象的重写函数时出现异常
GCC: exception when calling an overridden function of a static object
我正在使用 GCC 3.4.3。该设备是基于ARM9/ARM11的POS终端PAX S80。下一个测试代码编译正常,但在运行时调用重写函数时出现异常。
class TBase {
public:
int a;
virtual void Foo() {a = 1;}
void Exec() {Foo();}
};
class TDerived : public TBase {
public:
virtual void Foo() {a = 2;}
};
TBase *Base; //pointer to object in heap
TBase Base2; //static object
TDerived *Derived; //pointer to object in heap
TDerived Derived2; //static object
int main() {
Base = new TBase;
Base->Exec(); //this passes okay
Base2.Exec(); //this passes okay
Derived = new TDerived;
Derived->Exec(); //this passes okay
Derived2.Exec(); //here I get an exception and the app crashes
return 0;
}
这意味着我不能使用静态对象(Derived2)。是的,我可以在代码中创建对象 (Derived),但它会使代码复杂化,因为我需要使用 "new" 运算符实例化对象。
有什么技巧可以避免这个问题吗?
顺便说一下,我在 ARM926 的 Keil 编译器上没有这个问题。不幸的是,我无法为此设备选择编译器,只能选择 GCC 3.4.3。
感谢任何想法!
原因是静态对象的初始化没有发生。所以,我决定手动做。
首先,我将下一行添加到链接描述文件 (source):
__ctors_start__ = .;
KEEP(SORT(*)(.ctors))
__ctors_end__ = .;
其次,我调用了一个调用静态对象的所有构造函数的函数(source):
void do_ctor_calls() {
typedef void (*call_ctor_t)(void);
extern call_ctor_t __ctors_start__[];
extern call_ctor_t __ctors_end__[];
call_ctor_t * ctor_call = __ctors_start__;
while ((ctor_call < __ctors_end__)&&((unsigned int)*ctor_call!=0xFFFFFFFF)&&((unsigned int)*ctor_call!=0x00000000)) {
(*ctor_call)();
ctor_call++;
}
}
int main() {
do_ctor_calls();
/* My code here */
return 0;
}
最终,重写的函数可以正常工作,静态对象将照常运行。
感谢大家!
我正在使用 GCC 3.4.3。该设备是基于ARM9/ARM11的POS终端PAX S80。下一个测试代码编译正常,但在运行时调用重写函数时出现异常。
class TBase {
public:
int a;
virtual void Foo() {a = 1;}
void Exec() {Foo();}
};
class TDerived : public TBase {
public:
virtual void Foo() {a = 2;}
};
TBase *Base; //pointer to object in heap
TBase Base2; //static object
TDerived *Derived; //pointer to object in heap
TDerived Derived2; //static object
int main() {
Base = new TBase;
Base->Exec(); //this passes okay
Base2.Exec(); //this passes okay
Derived = new TDerived;
Derived->Exec(); //this passes okay
Derived2.Exec(); //here I get an exception and the app crashes
return 0;
}
这意味着我不能使用静态对象(Derived2)。是的,我可以在代码中创建对象 (Derived),但它会使代码复杂化,因为我需要使用 "new" 运算符实例化对象。
有什么技巧可以避免这个问题吗?
顺便说一下,我在 ARM926 的 Keil 编译器上没有这个问题。不幸的是,我无法为此设备选择编译器,只能选择 GCC 3.4.3。
感谢任何想法!
原因是静态对象的初始化没有发生。所以,我决定手动做。
首先,我将下一行添加到链接描述文件 (source):
__ctors_start__ = .;
KEEP(SORT(*)(.ctors))
__ctors_end__ = .;
其次,我调用了一个调用静态对象的所有构造函数的函数(source):
void do_ctor_calls() {
typedef void (*call_ctor_t)(void);
extern call_ctor_t __ctors_start__[];
extern call_ctor_t __ctors_end__[];
call_ctor_t * ctor_call = __ctors_start__;
while ((ctor_call < __ctors_end__)&&((unsigned int)*ctor_call!=0xFFFFFFFF)&&((unsigned int)*ctor_call!=0x00000000)) {
(*ctor_call)();
ctor_call++;
}
}
int main() {
do_ctor_calls();
/* My code here */
return 0;
}
最终,重写的函数可以正常工作,静态对象将照常运行。 感谢大家!