gcc與GnuCOBOL相互調用代碼

1、安裝GnuCOBOL函數

  得到最新版本的源代碼:.net

wget https://nchc.dl.sourceforge.net/project/open-cobol/gnu-cobol/2.0/gnu-cobol-2.0_rc-2.tar.gzcode

tar zxvf gnu-cobol-2.0_rc-2.tar.gzci

cd gnu-cobol-2.0/get

 ./configure --prefix=/opt/localit

make&sudo make installio

這裏/opt/local是個人安裝位置,你能夠換成本身的目錄,不過要設置好環境。如編譯

PATH,MANPATH,LD_LIBRARY_PATHclass

2、代碼gcc

cob程序片斷代碼

$ cat say.cob 
       IDENTIFICATION DIVISION.
       PROGRAM-ID. say.
       ENVIRONMENT DIVISION.
       DATA DIVISION.
       LINKAGE SECTION.
       01 hello PIC X(7).
       01 world PIC X(6).
       PROCEDURE DIVISION USING hello world.
           DISPLAY hello world.
           EXIT PROGRAM.

主程序c語言代碼

$ cat hello.c
#include <libcob.h>
extern int say(char *hello, char *world);
int
main()
{
	int ret;
	char hello[8] = "Hello, ";
	char world[7] = "world!";
	cob_init(0, NULL);
	ret = say(hello, world);
	return ret;
}

3、編譯運行

$ gcc -c `cob-config --cflags` hello.c
$ cobc -c -static say.cob
$ cobc -x -o hello hello.o say.o
$ ./hello 
Hello, world!

4、makefile

$ cat config.mk 

# Edit the following for your installation

CC	=	gcc
CXX	=	g++
COBC=	/opt/local/bin/cobc
COBF	=/opt/local/bin/cob-config

LFLAGS	=	`$(COBF) --libs`
INCPATH	=	`$(COBF) --cflags`
####### Implicit rules

.SUFFIXES: .o .c .cpp .cc .cxx .C .cob

.cpp.o:
	$(CXX) -c  -o "$@" "$<"

.cc.o:
	$(CXX) -c   -o "$@" "$<"

.cxx.o:
	$(CXX) -c -o "$@" "$<"

.C.o:
	$(CXX) -c  -o "$@" "$<"

.c.o:
	$(CC) -c  $(INCPATH) -o "$@" "$<"

.cob.o:
	$(COBC) -c  -static -o "$@" "$<"

 

CONFIG = ./config.mk
include $(CONFIG)

#==============================================================
# This program's code files
PRG		=hello
OBJS	=hello.o  say.o
#==============================================================
# File dependencies and rules

all:	$(PRG)

$(PRG): $(OBJS)
	$(COBC) -x -o $@ $(OBJS)
clean:
	rm -f *~
	rm -f *.o
	rm -f core
	rm -f $(PRG)

    $(COBC) -x -o $@ $(OBJS)

能夠改成:

    $(CC) -o $@ $(OBJS) $(LFLAGS) 

也就是說用cobc鏈接時不須要指明cobol庫的位置,而用gcc連接時須要

5、cobol調用c模塊

c代碼:

$ cat say.c 
#include <stdio.h>

int say(char *hello, char *world)
{
	int i;
	for(i = 0; i < 7; i++)
	  putchar(hello[i]);
	for(i = 0; i < 6; i++)
	  putchar(world[i]);
	putchar('\n');
	return 0;
}

cob主程序代碼

$ cat hello.cob 
       IDENTIFICATION DIVISION.
       PROGRAM-ID. hello.
       ENVIRONMENT DIVISION.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 hello PIC X(7) VALUE "Hello, ".
       01 world PIC X(6) VALUE "world!".
       PROCEDURE DIVISION.
       CALL "say" USING hello world.
       STOP RUN.

編譯運行:

$ cc -c say.c
$ cobc -c -static -x hello.cob
$ cobc -x -o hello hello.o say.o
$ ./hello 
Hello, world!

makefile:

只需修改config.mk

.cob.o:
    $(COBC) -c  -static -o "$@" "$<"

中加-x即改成:

.cob.o:
    $(COBC) -c  -static -x -o "$@" "$<"

不然出現main函數未定義引用錯誤。

固然

.c.o:

    $(CC) -c $(INCPATH) -o "$@" "$<

中的$(INCPATH)也能夠去掉

相關文章
相關標籤/搜索