なんとな~くしあわせ?の日記

「そしてそれゆえ、知識そのものが力である」 (Nam et ipsa scientia potestas est.) 〜 フランシス・ベーコン

libnkfを使う

iconv絡みでいろいろエラーが出て困ったので、よりポータブルな文字コード変換ライブラリを求めてlibnkfにたどり着いた。
libnkf

libnkfを使うついでに多段makeとMakefile中のif文の練習をする
configureスクリプトがあったけど新たにMakefileを書いた。


プロジェクトの構造

ファイル名称
libnkf               
  ├──libnkf          
  │    ├──libnkf.c    
  │    ├──libnkf.h    
  │    ├──Makefile    
  │    ├──nkf.h    
  │    └──utf8tbl.c    
  ├──libnkftest.exe    
  ├──main.cpp    
  └──Makefile    

libnkfのMakefile

# target and sources
TARGET  = libnkf.a
SOURCES = $(notdir $(shell find . -name '*.c'))
OBJECTS = $(SOURCES:.c=.o)

# basic command
CC		:= gcc
RM 		:= rm
AR      := ar

# compile option
CCFLAGS = -Wall -I/c/MinGW/include .
LDFLAGS  = -static -L/c/MinGW/lib
ARFLAG   = crsv

# make all
all:	$(TARGET) $(OBJECTS)
$(TARGET):
		$(CC) $^ -o $(LDFLAGS)
# suffix rule
.c.o:
	$(CC) $(CCFLAGS) -c $<
# build library
$(TARGET): $(OBJECTS) $(SOURCES)
	$(AR) $(ARFLAG) $(TARGET) $(OBJECTS)
	@echo "$(TARGET) make success"
# clean
.PHONY: clean
clean:
	$(RM) -f *.o $(TARGET)

libnkftestのMakefile

# target and sources
TARGET  = libnkftest
SOURCES = main.cpp
OBJECTS = $(SOURCES:.cpp=.o)
LIBNKF	= libnkf.a
NKFDIR	= libnkf

# basic command
MAKE	:= make
CXX		:= g++
RM 		:= rm

# compile option
CXXFLAGS = -Wall -I/c/MinGW/include -I. -I./libnkf
LDFLAGS  = -static -L/c/MinGW/lib -L libnkf -lnkf

# make all
all : $(TARGET) $(LIBNKF)

# target build
$(TARGET) : $(OBJECTS)
		$(CXX) $^ -o $@ $(LDFLAGS)
# suffix rule
.SUFFIXES: .cpp .o
.cpp.o:
		$(CXX) $(CXXFLAGS) -c $<

# library build
$(LIBNKF):
	@echo "library build"
	@if [ -f $(NKFDIR)/$(LIBNKF) ]; then \
		echo "libnkf found"; \
	else \
		echo "libnkf not found"; \
		$(MAKE) -C $(NKFDIR) ; \
	fi
# clean
.PHONY: clean
clean:
	$(RM) -f *.o $(TARGET)
	$(MAKE) -C libnkf clean

main.cppの中身

/*
 * main.cpp
 *
 *  Created on: 2012/06/29
 *      Author: learning
 */

#include <iostream>
#include "libnkf.h"

using namespace std;

int main() {
	// Shift_JIS文字列を設定する
	const char sjis[9] = {0x88,0xa2,0x82,0x70,0x90,0xb3,0x93,0x60};
	cout << "Shift_JIS文字列" << endl;
	cout << sjis << endl;

	// UTF-8に変換する
	char* utf8_str = new char[18];
	nkf(sjis, utf8_str, 18, "-S -w");

	cout << "UTF-8文字列" << endl;
	cout << utf8_str << endl;

	delete[] utf8_str;
}