Search code examples
javaimportjavacjava-package

javac adding classpath breaks my local class compilation


When I import a package to my MyLib class (which requires -cp to javac) I can no longer compile my MyMain class.

MyMain.java:

class MyMain
{
    public static void main (String [] args)
    {
        MyLib.do_stuff ();
    }
}

MyLib.java:

import com.google.gson.JsonElement;

class MyLib
{
    public static void do_stuff ()
    {
        System.out.println ("Hello.");
    }
}

When I javac MyLib.java I have do do it like this

javac -cp GSON_JAR_PATH MyLib.java

That works but if I

javac MyMain.java

I get

./MyLib.java:1: error: package com.google.gson does not exist
import com.google.gson.JsonElement;

but if I add -cp to the compilation command

javac -cp GSON_JAR_PATH MyMain.java

I get

MyMain.java:5: error: cannot find symbol
                MyLib.do_stuff ();
                ^
  symbol:   variable MyLib
  location: class MyMain

Solution

  • Use "-cp path1:path2" - colon separated. (semicolon works on windows) (the parameter to cp is quoted....

    javac -cp path1:path2 //or ; for windows.
    

    Note 1 - setting -cp overrides any existing CLASSPATH environment or default path setting.

    Note 2 - if no CLASSPATH setting then default is '.' - until the -cp overrides that.

    So in the posted case - the "." was set for path (either CLASSPATH or default) up until the -cp was used which overrode that default - so it needs to be added back in.