Use jmp_buf in multiple file

2019-09-21 07:07发布

For clearly, please view my sample

I have two files: main.cpp and myfunction.h

This is main.cpp

#include <setjmp.h>
#include <myfunction.h>

int main()
{
   if ( ! setjmp(bufJum) ) {
      printf("1");
      func();
   } else {
      printf("2");
   }
   return 0;
}

This is myfunction.h

#include <setjmp.h>
static jmp_buf bufJum;

int func(){
   longjum(bufJum, 1);
}

Now, I want my screen print "1" and then print "2", but this code is uncorrect! Please, help me! Thank you so much!

3条回答
来,给爷笑一个
2楼-- · 2019-09-21 07:21

You have a non-inline function defined in a .h file. While not illegal, this is pretty much always wrong.

You have a static global variable defined in a .h file. While not illegal, this is pretty much always wrong.

查看更多
男人必须洒脱
3楼-- · 2019-09-21 07:26

If you want to have it in multiple files, then you need to create two source files, not a single source file and a header file

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);
}

main.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 << "1\n";
        func();
    }
    else
    {
        std::cout << "2\n";
    }

    return 0;
}

If you are using GCC to compile these files, you can e.g. use this command line:

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

Now you have an executable program called myprogram which is made from two files.

查看更多
狗以群分
4楼-- · 2019-09-21 07:31

I don't know anything about setjmp, but you have at least one mistake in your code:

-#include <myfunction.h>
+#include "myfunction.h"
查看更多
登录 后发表回答