In Java, to use macros in the C language,

Asked 2 years ago, Updated 2 years ago, 69 views

Now I'm trying to convert the source written in C++ to Java.
I'm having trouble expanding and rewriting macros.
In particular, I am having trouble developing #define, #ifdef/#ifndef
Could someone tell me how to do this conversion?

java preprocessor

2022-09-30 20:33

3 Answers

Replacing macros in C 100% with java code is probably a waste.

So,
1. Convert macro-deployed sources to java.
That's the first plan.
Options such as -E-P for GCC.
For Visual C++, options like /EP
You can use to obtain deployed sources.
Example:
g++test.cpp-E-P-otest.cp

2.Apply the preprocessor of C to a java source containing macros.
That's the second plan.
If the preprocessor part is a separate program,
(For GCC, cpp is the preprocessor program.)
Copy the source code into the preprocessor program.
Example:
cpp test.java-o C2Java.java

If you change the extension
g++test.java.c-E-P-o Test.java
I think it's possible to do something like that.

In this case, you may not be able to apply 100% to the java code.


2022-09-30 20:33

No Java language is equivalent to a C language macro.

However, since ancient times, these translations have often been done with variables defined by public static final....

//C
#define MENU_WIDTH100
#define PAGE_WIDTH (MENU_WIDTH+500)
// Java
private static final int MENU_WIDTH = 100;
private static final int PAGE_WIDTH = MENU_WIDTH+50;
//C
# define multiple (d1, d2) (d1*d2)
// Java
private static double multiple (double1, double2) {return d1*d2;}
//C
#define IS_AMIGA500
...
# ifdef IS_AMIGA500
...
#endif

-Decide upon compilation

The if(...){...} branch to the private static final boolean constant is optimized by the compiler (and depending on the running environment), so the following methods are recommended:

// Java
private static final boolean IS_AMIGA500 = true;

...
    if(IS_AMIGA500){
        ...
    }

-Decide at runtime

Alternatively, you can pass a constant value to the Java VM at runtime.

// Java
private static final boolean IS_AMIGA500 = "true".equals(System.getProperty("IS_AMIGA500"));

...
    if(IS_AMIGA500){
        ...
    }
$#Console
$ java-DIS_AMIGA500 = true MainClass


2022-09-30 20:33

C++ applications have become DLLs, so how about calling them JNI from Java?


2022-09-30 20:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.