在多个文件中使用jmp_buf

Use jmp_buf in multiple file

本文关键字:jmp buf 文件      更新时间:2023-10-16

为了清楚起见,请查看我的样本

我有两个文件:main.cpp和myfunction.h

这是主要的.cpp

#include <setjmp.h>
#include <myfunction.h>
int main()
{
   if ( ! setjmp(bufJum) ) {
      printf("1");
      func();
   } else {
      printf("2");
   }
   return 0;
}

这是myfunction.h

#include <setjmp.h>
static jmp_buf bufJum;
int func(){
   longjum(bufJum, 1);
}

现在,我想让我的屏幕打印"1",然后打印"2",但此代码不正确!求求你,帮帮我!非常感谢!

如果要将其放在多个文件中,则需要创建两个文件,而不是单个源文件和一个头文件

myfunction.cpp:

#include <setjmp.h>
extern jmp_buf bufJum;  // Note: `extern` to tell the compiler it's defined in another file
void func()
{
    longjmp(bufJum, 1);
}

主.cpp:

#include <iostream>
#include <setjmp.h>
jmp_buf bufJum;  // Note: no `static`
void func();  // Function prototype, so the compiler know about it
int main()
{
    if (setjmp(bufJum) == 0)
    {
        std::cout << "1n";
        func();
    }
    else
    {
        std::cout << "2n";
    }
    return 0;
}

如果您使用 GCC 编译这些文件,则可以使用以下命令行:

$ g++ -Wall main.cpp myfunction.cpp -o myprogram

现在你有一个名为myprogram的可执行程序,它由两个文件组成。

我对 setjmp 一无所知,但您的代码中至少有一个错误:

-#include <myfunction.h>
+#include "myfunction.h"

您在 .h 文件中定义了非内联函数。 虽然不违法,但这几乎总是错误的。

您在 .h 文件中定义了静态全局变量。 虽然不违法,但这几乎总是错误的。