views:

515

answers:

3

Hi,

I read the Sun documentation and a lot of Q/A on SO but I'm still a little bit confuse regarding the differences between the javac options -cp and -sourcepath.

Let say I have this directory structure:
c:\Java\project1\src (where the .java source files are)
c:\Java\project1\bin (where the .class will be or are already)

The class source MainClass.java is in a package "com.mypackage" and the directory structure is ok in src.

I'm in the project1 directory. I run
c:\Java\Project1\javac -d bin -sourcepath src src/com/mypackage/MainClass.java
or
c:\Java\Project1\javac -d bin -classpath src src/com/mypackage/MainClass.java
and I obtain the same result. In verbose mode, the search path for source files is src in both cases.

If anybody could help me figure out the specifics of these options, it would be great.

Thank you.

+2  A: 
  • sourcepath is where is the root of your code to compile
  • classpath can contains your code but also the libraries you need
Kartoch
Thank you for your answer.
Alex
+1  A: 

CLASSPATH tells the compiler and the class loader where to look for the .class files it needs.

Sourcepath is something I don't use so much. I believe it's optional, because usually the current directory is the sourcepath. CLASSPATH is not.

duffymo
+5  A: 
 -classpath classpath

Set the user class path, overriding the user class path in the CLASSPATH environment variable. If neither CLASSPATH or -classpath is specified, the user class path consists of the current directory.

If the -sourcepath option is not specified, the user class path is searched for source files as well as class files.

-sourcepath sourcepath

Specify the source code path to search for class or interface definitions. As with the user class path, source path entries are separated by semicolons (;) and can be directories, JAR archives, or ZIP archives. If packages are used, the local path name within the directory or archive must reflect the package name.

Note that classes found through the classpath are subject to automatic recompilation if their sources are found.

stacker
Thank you for your answer. The last sentence is what I was looking for: automatic recompilation of the source files found in the cp. I verified the date of modification of the .class files in the bin directory and it follows this principle! Here is the big difference between the 2 options. The compiling time gives this clue too. Thank you!
Alex