Getting Started with ANTLR4 and C++

Viewed 3404

First time question asker here, so bear with me. So I've got a grammar file from the grammars repository that I'm trying to use with C++. (Developing on macOS). I have no issue generating the lexer and parser using ANTLR. But after that, I have no idea how to run/use the resulting .cpp and .h files. I understand that there is an antlr runtime that I must download, and I have done so from the antlr.org website (gives me two folders, antlr4-runtime and lib), but my novice understanding of C++ seems to be preventing me from getting any further than that. How do I use the runtime to work with these files? I'm not using an IDE, just g++ from the command line. Thank you for any help!

1 Answers

I found this guide helpful: Getting Started with ANTLR in C++. (Ah, saw @ggorlen's comment after.)

If you scroll down on that page to a little past halfway, there's a section titled How to Use ANTLR in C++. I think that's where you are.

I'll copy that example over as SO generally prefers this. Say this is your main.cpp:

#include <iostream>
#include "antlr4-runtime/antlr4-runtime.h"
#include "antlr4-runtime/SceneLexer.h"
#include "antlr4-runtime/SceneParser.h"
#include "ImageVisitor.h"

using namespace std;
using namespace antlr4;
int main(int argc, const char* argv[]) {

    std::ifstream stream;
    stream.open("input.scene");

    ANTLRInputStream input(stream);
    SceneLexer lexer(&input);
    CommonTokenStream tokens(&lexer);
    SceneParser parser(&tokens);    
    SceneParser::FileContext* tree = parser.file();
    ImageVisitor visitor;
    Scene scene = visitor.visitFile(tree);
    scene.draw();
    return 0;
}

You want to include your lexer and parser .h (header) files instead of the SceneLexer/Parser in the example, and also include antlr4-runtime.h. Then run g++ on all your .cpp files, e.g.

$ g++ main.cpp YourLexer.h YourParser.h
Related