Skip to content
Advertisement

GCJ throws error: “Undefined reference to main” when compiling

I´d wanted to compile a simple Java “Hello World” program like it was repesented on the GeeksforGeeks Hello World Tutorial, by using gcj in Linux Ubuntu. This is the source code:

class HelloWorld 
{ 
    public static void main(String args[]) 
    { 
        System.out.println("Hello, World"); 
    } 
} 

But gcj threw two errors:

  1. (.text+0x18): undefined reference to main
  2. collect2: error: ld returned 1 exit status

Original output from the terminal:

gcj -o helloworld HelloWorld.java
/usr/lib/gcc/i686-linux-gnu/4.6/../../../i386-linux-gnu/crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'
collect2: error: ld returned 1 exit status

I´d take attention on the requirement, that the .java file should be named after the class which holds main:

Important Points :

  • The name of the class defined by the program is HelloWorld, which is same as name of file(HelloWorld.java). This is not a coincidence. In Java, all codes must reside inside a class and there is at most one public class which contain main() method.
  • By convention, the name of the main class(class which contain main method) should match the name of the file that holds the program.

What am I doing wrong?

Advertisement

Answer

You are missing the --main= option, from the documentation, this option is used when linking to specify the name of the class whose main method should be invoked when the resulting executable is run.

gcj -o helloworld --main=HelloWorld HelloWorld.java
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement