0

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

Goldengirl
  • 957
  • 4
  • 10
  • 30
  • 1
    Your question is a bit unclear. You want to generate C code, right? To generate the hello world program you just put its contents into a template and either write it to the console (using ```println```) or write it to a file. – Franz Becker Jul 22 '15 at 06:14
  • @FranzBecker :Thank you so much for your reply :) The hello world was an example. What I really meant was any information where I could read up a bit more on Xtend. Since the official documentation does not have lot many examples. I want to understand the syntax of the Java tamplytes. Could you maybe suggest something? – Goldengirl Jul 22 '15 at 06:20

1 Answers1

1

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

Franz Becker
  • 705
  • 5
  • 8
  • THank you again. I tried running your program but it gives me an error saying "Selection does not contain a main type". :( – Goldengirl Jul 22 '15 at 06:53
  • 1
    If you have Xtend properly installed in your Eclipse IDE you can simple select "Run As - Java Application". Another stackoverflow question with screenshots: http://stackoverflow.com/questions/16225177/error-selection-does-not-contain-a-main-type - let me know if that solves your problem. – Franz Becker Jul 22 '15 at 06:58
  • The file was not part of the src file, and thus the error. THank you once again :) – Goldengirl Jul 22 '15 at 07:02