Development Tip

자바 컴파일은 정확히 어떻게 이루어 집니까?

yourdevel 2020. 12. 8. 20:06
반응형

자바 컴파일은 정확히 어떻게 이루어 집니까?


자바 컴파일 과정에서 혼란 스러움

좋아, 나는 이것을 안다 : 우리는 자바 소스 코드를 작성하고, 플랫폼 독립적 인 컴파일러는 그것을 바이트 코드로 변환하고, 플랫폼 의존적 인 jvm은 그것을 기계 코드로 변환합니다.

그래서 처음부터 자바 소스 코드를 작성합니다. 컴파일러 javac.exe는 .exe 파일입니다. 이 .exe 파일은 정확히 무엇입니까? 자바 컴파일러가 자바로 작성되지 않았는데, 어떻게 실행하는 .exe 파일이 있습니까? 컴파일러 코드가 작성되면 자바 코드를 실행하는 jvm의 작업이기 때문에 컴파일 단계에서 컴파일러 코드가 어떻게 실행됩니까? 언어 자체가 어떻게 자체 언어 코드를 컴파일 할 수 있습니까? 나에게 그것은 모두 닭고기와 달걀 문제처럼 보입니다.

이제 .class 파일에는 정확히 무엇이 포함되어 있습니까? 텍스트 형식의 추상 구문 트리입니까, 표 형식 정보입니까, 무엇입니까?

아무도 내 자바 소스 코드가 기계 코드로 변환되는 방법에 대해 명확하고 자세한 방법을 말할 수 있습니다.


알겠습니다. 우리는 자바 소스 코드를 작성합니다. 플랫폼에 독립적 인 컴파일러는이를 바이트 코드로 변환합니다.

실제로 컴파일러 자체가 작동하는 기본 실행 파일 (따라서 javac.exe)로. 사실, 소스 파일을 바이트 코드로 변환합니다. 바이트 코드는 Java Virtual Machine을 대상으로하기 때문에 플랫폼 독립적입니다.

그런 다음 플랫폼에 따라 달라지는 jvm은이를 기계어 코드로 변환합니다.

항상 그런 것은 아닙니다. Sun의 JVM에는 클라이언트와 서버의 두 가지 jvm이 있습니다. 둘 다 가능하지만 반드시 네이티브 코드로 컴파일해야하는 것은 아닙니다.

그래서 처음부터 자바 소스 코드를 작성합니다. 컴파일러 javac.exe는 .exe 파일입니다. 이 .exe 파일은 정확히 무엇입니까? 자바 컴파일러가 자바로 작성되지 않았는데, 어떻게 실행하는 .exe 파일이 있습니까?

exe파일은 래핑 된 자바 바이트 코드입니다. 편의상-복잡한 배치 스크립트를 피하는 것입니다. JVM을 시작하고 컴파일러를 실행합니다.

컴파일러 코드가 작성되면 자바 코드를 실행하는 jvm의 작업이기 때문에 컴파일 단계에서 컴파일러 코드가 어떻게 실행됩니까?

이것이 바로 래핑 코드가하는 일입니다.

언어 자체가 어떻게 자체 언어 코드를 컴파일 할 수 있습니까? 나에게 그것은 모두 닭고기와 달걀 문제처럼 보입니다.

사실, 언뜻보기에 혼란 스럽습니다. 하지만 Java의 관용구 만이 아닙니다. Ada의 컴파일러는 Ada 자체로도 작성되었습니다. "닭과 계란 문제"처럼 보일지 모르지만 실제로는 부트 스트랩 문제 일뿐입니다.

이제 .class 파일에는 정확히 무엇이 포함되어 있습니까? 텍스트 형식의 추상 구문 트리입니까, 표 형식 정보입니까, 무엇입니까?

추상 구문 트리가 아닙니다. AST는 메모리의 코드를 나타 내기 위해 컴파일 할 때 토크 나이저와 컴파일러에서만 사용됩니다. .class파일은 어셈블리와 같지만 JVM 용입니다. JVM은 가상 머신만을 대상으로하는 특수 머신 언어를 실행할 수있는 추상 머신입니다. 가장 간단한 점에서 .class파일은 일반 어셈블리와 매우 유사한 구조를 가지고 있습니다. 처음에는 모든 정적 변수가 선언 된 다음 extern 함수 시그니처 테이블과 마지막으로 기계 코드가 제공됩니다.

정말로 궁금하다면 "javap"유틸리티를 사용하여 classfile을 파헤칠 수 있습니다. 다음은 호출의 샘플 (난독 화 된) 출력입니다 javap -c Main.

0:   new #2; //class SomeObject
3:   dup
4:   invokespecial   #3; //Method SomeObject."<init>":()V
7:   astore_1
8:   aload_1
9:   invokevirtual   #4; //Method SomeObject.doSomething:()V
12:  return

그래서 당신은 그것이 정말로 무엇인지 이미 알고 있어야합니다.

아무도 내 자바 소스 코드가 기계 코드로 변환되는 방법에 대해 명확하고 자세한 방법을 말할 수 있습니다.

지금 당장은 더 명확해야한다고 생각하지만 여기에 짧은 요약이 있습니다.

  • javac소스 코드 파일을 가리 키도록 호출 합니다. javac 의 내부 판독기 (또는 토크 나이저)는 파일을 읽고 그로부터 실제 AST를 빌드합니다. 모든 구문 오류는이 단계에서 발생합니다.

  • javac아직 작업이 완료되지 않았습니다. AST가 있으면 실제 컴파일을 시작할 수 있습니다. 방문자 패턴을 사용하여 AST를 탐색하고 코드에 의미 (의미)를 추가하기 위해 외부 종속성을 해결합니다. 완성 된 제품은 .class바이트 코드가 포함 파일 로 저장됩니다 .

  • 이제 일을 실행할 시간입니다. java.class 파일의 이름으로 호출 합니다. 이제 JVM이 다시 시작되지만 코드 해석 합니다. JVM은 귀하의 추상 바이트 코드를 원시 어셈블리로 컴파일하거나 컴파일하지 않을 수 있습니다. Just In Time 컴파일과 함께 Sun의 HotSpot 컴파일러는 필요한 경우 그렇게 할 수 있습니다. 실행중인 코드는 JVM에 의해 지속적으로 프로파일 링되고 특정 규칙이 충족되면 네이티브 코드로 재 컴파일됩니다. 가장 일반적으로 코드는 기본적으로 컴파일되는 첫 번째 코드입니다.

편집 : javac하나가 없으면 다음과 비슷한 것을 사용하여 컴파일러를 호출해야합니다.

%JDK_HOME%/bin/java.exe -cp:myclasspath com.sun.tools.javac.Main fileToCompile

보시다시피 Sun의 개인 API를 호출하므로 Sun JDK 구현에 바인딩됩니다. 그것은 그것에 의존하는 빌드 시스템을 만들 것입니다. 다른 JDK로 전환 한 경우 (위키에는 Sun이 아닌 5 개가 나열되어 있음) 위 코드를 업데이트하여 변경 사항을 반영해야합니다 (컴파일러가 com.sun.tools.javac 패키지에있을 가능성이 낮기 때문). 다른 컴파일러는 네이티브 코드로 작성 될 수 있습니다.

따라서 표준 방법은 javacJDK와 함께 래퍼를 제공하는 것입니다.


자바 컴파일러가 자바로 작성되지 않았는데, 어떻게 실행하는 .exe 파일이 있습니까?

이 정보는 어디서 얻습니까? javac실행 파일이 어떤 프로그래밍 언어로 작성 될 수있는 것이 중요합니다 모든이가집니다 실행 점이다, 무관 .java에 파일을 .class파일입니다.

.class 파일의 이진 사양에 대한 자세한 내용은 Java 언어 사양 의 다음 장이 유용 할 수 있습니다 (약간 기술적 일 수 있음).

다음 을 다루는 가상 머신 사양살펴볼 수도 있습니다 .


컴파일러 javac.exe는 .exe 파일입니다. 이 .exe 파일은 정확히 무엇입니까? 자바 컴파일러가 자바로 작성되지 않았는데, 어떻게 실행하는 .exe 파일이 있습니까?

The Java compiler (at least the one that comes with the Sun/Oracle JDK) is indeed written in Java. javac.exe is just a launcher that processes the command line arguments, some of which are passed on to the JVM that runs the compiler, and others to the compiler itself.

If the compiler code is written is java, then how come compiler code is executed at the compilation stage, since its the job of the jvm to execute java code. How can a language itself compile its own language code? It all seems like chicken and egg problem to me.

Many (if not most) compilers are written in the language they compile. Obviously, at some early stage the compiler itself had to be compiled by something else, but after that "bootstrapping", any new version of the compiler can be compiled by an older version.

Now what exactly does the .class file contain? Is it a abstract syntax tree in text form, is it tabular information, what is it?

The details of the class file format are described in the Java Virtual Machine specification.


Well, javac and the jvm are typically native binaries. They're written in C or whatever. It's certainly possible to write them in Java, just you need a native version first. This is called "boot strapping".

Fun fact: Most compilers that compile to native code are written in their own language. However, they all had to have a native version written in another language first (usually C). The first C compiler, by comparison, was written in Assembler. I presume that the first assembler was written in machine code. (Or, using butterflies ;)

.class files are bytecode generated by javac. They're not textual, they're binary code similar to machine code (but, with a different instruction set and architechture).

The jvm, at run time, has two options: It can either intepret the byte code (pretending to be a CPU itself), or it can JIT (just-in-time) compile it into native machine code. The latter is faster, of course, but more complex.


The .class file contains bytecode which is sort of like very high-level Assembly. The compiler could very well be written in Java, but the JVM would have to be compiled to native code to avoid the chicken/egg problem. I believe it is written in C, as are the lower levels of the standard libraries. When the JVM runs, it performs just-in-time compilation to turn that bytecode into native instructions.


Short Explanation

Write code on a text editor, save it in a format that compiler understands - ".java" file extension, javac (java compiler) converts this to ".class" format file (byte code - class file). JVM executes the .class file on the operating system that it sits on.

Long Explanation

Always remember java is not the base language that operating system recognizes. Java source code is interpreted to the operating system by a translator called Java Virtual Machine (JVM). JVM cant understand the code that you write in a editor, it needs compiled code. This is where a compiler comes into picture.

Every computer process indulges in memory manipulation. We cant just write code in a text editor and compile it. We need to put it in the computer's memory, i.e save it before compiling.

How will the javac (java compiler) recognize the saved text as the one to be compiled? - We have a separate text format that the compiler recognizes, i.e .java. Save the file in .java extension and the compiler will recognize it and compile it when asked.

What happens while compiling? - Compiler is a second translator(not a technical term) involved in the process, it translates user understood language(java) into JVM understood language(Byte code - .class format).

What happens after compiling? - The compiler produces .class file that JVM understands. The program is then executed, i.e the .class file is executed by JVM on the operating system.

Facts you should know

1) Java is not multi-platform it is platform independent.

2) JVM is developed using C/C++. One of the reason why people call Java a slower language than C/C++

3) Java byte code (.class) is in "Assembly Language", the only language understood by JVM. Any code that produces .class file on compilation or generated Byte code can be run on the JVM.


Windows doesn't know how to invoke Java programs before installing a Java runtime, and Sun chose to have native commands which collect arguments and then invoke the JVM instead of binding the jar-suffix to the Java engine.


The compiler was originally written in C with bits of C++ and I assume that it still is (why do you think the compiler is written in Java as well?). javac.exe is just the C/C++ code that is the compiler.

As a side point you could write the compiler in java, but you're right, you have to avoid the chicken and egg problem. To do this you'd would typically write one or more bootstrapping tools in something like C to be able to compile the compiler.

The .class file contains the bytecodes, the output of the javac compilation process and these are the instructions that tell the JVM what to do. At runtime these bytecodes have are translated to native CPU instructions (machine code) so they can execute on the specific hardware under the JVM.

To complicate this a little, the JVM also optimises and caches machine code produced from the bytecodes to avoid repeatedly translating them. This is known as JIT compilation and occurs as the program is running and bytecodes are being interpreted.


  1. .java file
  2. compiler(JAVA BUILD)
  3. .class(bytecode)
  4. JVM(system software usually build with 'C')
  5. OPERATING PLATFORM
  6. PROCESSOR

참고URL : https://stackoverflow.com/questions/3406942/how-exactly-does-java-compilation-take-place

반응형