Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

compiler construction - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should pass all the the .cpp files, and no .hpp, to the compile command. The .hpp will be automatically included by the preprocessor. If you don't do it (you are not including Ob.cpp in your command), then it can't find the definition of the functions contained in them.

So your compilation command should be this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...