Flex-Bison C ++中的对象实例

问题描述

我的 main.hpp 看起来像这样:

#include "json.tab.h"
#include "ob.hpp"

extern Ob *ob;

在我的 test.l 中,我写道:

%{
    #include "main.hpp"
%}


%token  KEY
%token  COMMA

%%
KEY_SET         : KEY                                                 {ob->someOp();}
                | KEY_SET COMMA KEY                                   {ob->someOp();}
%%

但这给了我:

C:\......c:(.text+0x37a): undefined reference to `ob'
C:\......c:(.text+0x38e): undefined reference to `Ob::someop()'

那么如何在解析器中的任何地方调用该Ob对象?

我的Ob类( Ob.hpp ):

#include <bits/stdc++.h>
using namespace std;

#ifndef O_H_
#define O_H_

using namespace std;

class Ob {
public:
    Ob();
    ~Ob();
    someop();
};

#endif /*O_H_*/

Ob.cpp

Ob::someop()
{
    cout << "c++ is lit" << endl;
}

现在,我已将Ob中的所有方法设为静态,因此无需实例。我的构建规则如下所示:

g++ lex.yy.c test.tab.c main.cpp *.hpp -o test.exe

我使解析器生成器变得简单,没有任何方法调用,并且运行正常,没有错误,没有警告:

%%
KEY_SET         : KEY     
                | KEY_SET COMMA KEY    
%%

当我添加{Ob::someOp();}时,它又给了我同样的错误

我所有的代码在这里https://gist.github.com/maifeeulasad/6d0ea58cd70fbe255a4834eb46f2e1fd

解决方法

您应该将所有.cpp文件(而不是.hpp)传递给compile命令。 .hpp将由预处理器自动包含。如果您不这样做(您的命令中没有包含Ob.cpp),那么它将找不到其中包含的功能的定义。

因此,您的编译命令应为:

g++ lex.yy.c test.tab.c main.cpp Ob.cpp -o test.exe
,

解析器生成器如下所示:

%{
    #include<stdio.h>
    #include "main.h"
    #include "json.h"
    using namespace Maifee;
%}
...
meaw           : INTEGER               {Json::ok();}

标题:

#ifndef JSON_H
#define JSON_H

#include <bits/stdc++.h>
using namespace std;

namespace Maifee{

class Json {
public:
    static void ok();
};
#endif // JSON_H

cpp文件:

#include <bits/stdc++.h>
#include "json.h"

using namespace std;
using namespace Maifee;

void Json::ok()
{
    //whatever here
}