Search code examples
c++compiler-constructionlinker-errorsbisonflex-lexer

Instance of object in flex-bison c++


My main.hpp looks like this :

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

extern Ob *ob;

In my test.l, I wrote :

%{
    #include "main.hpp"
%}


%token  KEY
%token  COMMA

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

But this gives me :

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

So how can I call that Ob object from anywhere in my parser?

My Ob class(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_*/

And Ob.cpp:

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

Now I have made all method in Ob static, so that no need to have an instance. And my build rule looks something like this :

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

And I made the parser generator plain, without any method call, and it works fine, no error, no warning :

%%
KEY_SET         : KEY     
                | KEY_SET COMMA KEY    
%%

And when I added {Ob::someOp();}, then it gives me the same error again.

All of my codes are here : https://gist.github.com/maifeeulasad/6d0ea58cd70fbe255a4834eb46f2e1fd


Solution

  • The parser generator looks like this :

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

    Header:

    #ifndef JSON_H
    #define JSON_H
    
    #include <bits/stdc++.h>
    using namespace std;
    
    namespace Maifee{
    
    class Json {
    public:
        static void ok();
    };
    #endif // JSON_H
    

    The cpp file :

    #include <bits/stdc++.h>
    #include "json.h"
    
    using namespace std;
    using namespace Maifee;
    
    void Json::ok()
    {
        //whatever here
    }