在多个文件中使用jmp_buf [英] Use jmp_buf in multiple file

查看:306
本文介绍了在多个文件中使用jmp_buf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显然,请查看我的样本

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

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

这是main.cpp

This is main.cpp

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

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

这是myfunction.h

This is myfunction.h

#include <setjmp.h>
static jmp_buf bufJum;

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

现在,我要我的屏幕打印1,然后打印2 ,但这段代码是不正确的!
请帮帮我!
非常感谢!

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

推荐答案

如果你想要在多个文件中,那么你需要创建两个源文件,不是单个源文件和头文件

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:

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

如果您使用GCC编译这些文件,使用这个命令行:

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

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

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

这篇关于在多个文件中使用jmp_buf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆