วันอังคารที่ 29 กันยายน พ.ศ. 2558

ใช้ C Preprocessor กับ Golang !!!! จะบร้า.....หรอ...

ก็พอจะเข้าใจนะครับว่า Code Go ต้องดูและเข้าใจง่าย แต่พอมีความสามารถในการ Cross compile ที่สามารถ compile ข้าม  ARCH ได้นี่ ผมก็เริ่มต้องการ Preprocessor อย่างแรง...

ไปไล่ดู ก็เห็นคนขอกันเยอะไปหมด อาจอยู่ในคิว features แหละ ไม่ได้ตามต่อ แต่ต้องการใช้ตอนนี้ นี่สิ...

Code บน OSX แล้ว Compile ไปทำงานบน Pi2 ด้วย

$ env GOOS=linux GOARCH=arm GOARM=7 go build BlinkBlink

จากนั้น

$ sshpass -p 'raspberry' scp Blink pi@192.168.1.50:~/

สะดวกสบาย... จริงๆ

แต่ปัญหาคือ อยากให้มันทำงานบน OSX ด้วยไง เลยอยาก #ifdef เอา code IO บางส่วนออก

Golang ทำไม่ได้!!!

อ้าว......

ไม่เป็นไรครับ คิดไม่ออก ใช้ C Preprocessor เลย....
https://gcc.gnu.org/onlinedocs/cpp/Invocation.html

ผม code แบบนี้ครับ

package main

import (
"fmt"
#ifdef RPI2
"github.com/stianeikeland/go-rpio"
#endif
"os"
"time"
)

#ifdef RPI2
var (
// Use mcu pin 17, corresponds to physical pin 11  on the pi
pin1 = rpio.Pin(17)
pin2 = rpio.Pin(18)
)
#endif

func main() {
#ifdef RPI2
        InitPIIO()
#else
        fmt.Println("Ignore hardware initialize")
#endif
}

#ifdef RPI2
func InitPIIO() {
        fmt.Println("InitPIIO")
}
#endif

แล้วตั้งชื่อ main.go.p เรียก C Preprocessor

$ cpp -P main.go.p main.go

จะได้ main.go แบบนี้

package main

import (
            "fmt"



                    "os"
                        "time"
       )









func main() {



                        fmt.Println("Ignore hardware initialize")

}

C Preprocessor จะเอา code ใน #ifdef RPI2 ออกไป

ทีนี้พอจะ Build ไปทำงานบน RPI2 เราก็

$ cpp -DRPI2 -P main.go.p main.go

จะได้ main.go แบบนี้

package main

import (
            "fmt"

                "github.com/stianeikeland/go-rpio"

                    "os"
                        "time"
       )


var (
            // Use mcu pin 17, corresponds to physical pin 11  on the pi
            pin1 = rpio.Pin(17)
                pin2 = rpio.Pin(18)
    )


func main() {

            InitPIIO()



}


func InitPIIO() {
            fmt.Println("InitPIIO")
}

ไม่ง้อ Native Golang Preprocessor (ตอนนี้) แล้วเว๊ย.......


ไม่มีความคิดเห็น:

แสดงความคิดเห็น