简体   繁体   English

如何干净地退出混合C / C ++的程序

[英]How to exit a program with mixed C/C++ cleanly

I'm interfacing a C program ( main() is in C) with C++. 我正在使用C ++连接C程序( main()在C中)。 At some points in my code I want to stop execution of the program. 在我的代码中的某些点我想停止执行程序。 Now I'd like to know, how can I do this cleanly? 现在我想知道,我怎么能干净利落地做到这一点?

At the moment I call std::terminate() but more out of a lack of better ideas. 目前我调用std::terminate()但更多的是缺乏更好的想法。 The main thing that bugs me isn't even that I'm not freeing the memory (because it's freed anyway on program termination, right?) but that the MSVS Just-in-time Debugger pops up and I get an ugly error message about terminating the runtime in an unusual way. 让我烦恼的主要问题是,即使我没有释放内存(因为它在程序终止时也被释放了,对吧?)但是MSVS即时调试器会弹出,我收到一个丑陋的错误消息以不寻常的方式终止运行时。

EDIT: As this has caused confusion: Returning from main() with return 0 is not possible in this case. 编辑:因为这引起了混乱:在这种情况下,不能从main() return 0

If you concern about cleaning up and invoking destuctors then 如果您担心清理和调用destuctors然后

exit(EXIT_SUCCESS); // or EXIT_FAILURE

is the best choice between exit , terminate and abort . exitterminateabort之间的最佳选择。

  • Function exit calls descructors and cleans up the automatic storage objects (The object which declared in the global scope). 函数exit调用descructors并清理自动存储对象(在全局范围内声明的对象)。 It also calls the functions passed to atexit . 它还调用传递给atexit的函数。

  • Function abort is useful for abnormal exits and will not clean up anything. 函数abort对异常退出很有用,不会清理任何东西。 It doesn't call the functions passed to atexit . 它不会调用传递给atexit的函数。

  • Function terminate does not exist in C. It's useful when you have an exception and you can't handle it but finishing the program. C中不存在函数terminate 。当您遇到异常并且无法处理它但完成程序时,它很有用。

main function is where it starts, main function is where it should end usually. main函数是它启动的地方, main函数通常是它应该结束的地方。 If you use return 0; 如果你使用return 0; it indicates succesful exit. 它表明成功退出。

int main(void) {
    //init
    //do stuff
    //deinit
    return 0; // bye bye
}

You could also use exit(0); 你也可以使用exit(0); , but if your exit points are scattered all over the place it makes things harder to debug. ,但如果您的出口点遍布整个地方,则会使调试变得更加困难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM