Goldengirl
Goldengirl

Reputation: 967

How to use Xtend Template with a C hello World?

I am a newbie Java Programmer. I am trying to understand the working of the Xtend template. I have read that these templates can be used to generate a java code from a simple C program. Could somebody kindly give me an idea how this simple C program as shown below could be converted into a Java program..

  #include<stdio.h>

  main()
  {
      printf("Hello World");
  }

The Xtend template looks something like this :

     def someHTML(String content) '''
  <html>
    <body>
      «content»
    </body>
  </html>
'''

C

Upvotes: 0

Views: 715

Answers (1)

Franz Becker
Franz Becker

Reputation: 705

A simple example could look like this:

package com.example

class HelloWorld {

    def static void main(String[] args) {
        val instance = new HelloWorld
        println(instance.generateC)
    }

    def String generateC() '''
        #include<stdio.h>

        main()
            intf("Hello World");
        }
    '''

}

This will print the generate code to your console. You can also generate to a file, for example:

def static void main(String[] args) {
    val instance = new HelloWorld
    val code = instance.generateC
    val file = new File("helloworld.c")
    Files.write(code, file, Charsets.UTF_8)
    println("Generated code to " + file.absolutePath)
}

The official documentation can be found here: https://eclipse.org/xtend/documentation/203_xtend_expressions.html#templates and there are some blog posts and stackoverflow questions around this topic as well.

You can also find information in the Xtext documentation since Xtend is used there for code generation as well, e.g. http://www.eclipse.org/Xtext/documentation/103_domainmodelnextsteps.html#tutorial-code-generation

Upvotes: 1

Related Questions