在C ++程序中使用C共享库

时间:2013-11-15 08:07:08

标签: c++ c linux gcc g++

我无法在用g ++编译的程序中链接用gcc编译的共享库。 我有一个使用以下命令通过gcc编译的共享库:

build-library: activate-library-mode activate-debug-mode build-headers build-c-files build-exe-files
@echo -e $(cyan)generating shared library...$(plain)
@for exefile in $(exefiles); do\
    echo "$(CC) $(DEBUG) $(EXELIBFLAG) -o $(BINDIR)lib`basename $$exefile .c`.so $(wildcard $(OBJDIR)*.o)";\
    $(CC) $(DEBUG) $(EXELIBFLAG) -o $(BINDIR)lib`basename $$exefile .c`.so $(wildcard $(OBJDIR)*.o);\
done

其中:

  • CC = GCC
  • DEBUG = -g
  • EXELIBFLAG = -shared
  • BINDIR =仓/
  • exefiles = SRC / main.c中
  • * .o文件使用-fPIC编译,-g,-Wall一些-I和-c选项

因此,产生的呼叫是:

gcc -g -shared -o bin/libmain.so obj/ClassElement.o obj/ClassHashTable.o obj/ClassHTCell.o obj/IdentifierList.o obj/LabelClassType.o obj/LabelHashTable.o obj/LabelHTCell.o obj/Label.o obj/lexer.o obj/lex-tools.o obj/LexVal.o obj/LocalResourceElement.o obj/LocalResourceHashTable.o obj/LocalResourceHTCell.o obj/main.o obj/main-tools.o obj/memory-tools.o obj/NodeType.o obj/parser.o obj/parser-tools.o obj/PassMode.o obj/ResourceClassType.o obj/ResourceElement.o obj/ResourceHashTable.o obj/ResourceHTCell.o obj/schemaClassType.o obj/schema.o obj/semantic.o obj/SyntaxNode.o

我在LD_LIBRARY_PATH中添加了共享库的路径,仅用于测试目的:

LD_LIBRARY_PATH=/home/koldar/Documents/git/Kaboom/custom-object-language/CustomProgrammingLanguage/bin:
export LD_LIBRARY_PATH

然后,以下程序使用该库:

#include "Label.h"

int main(){
    Plabel l=initLabel("hello",LABEL_PACKAGE); //use library function
    printf("OK.\n");
    return 0;
}

该程序使用g ++通过以下命令编译:

g++ -I /home/koldar/Documents/git/Kaboom/custom-object-language/CustomProgrammingLanguage/include/ -I /home/koldar/Documents/git/Kaboom/custom-object-language/KaboomTest/cute/ -L /media/Dati/Users/Koldar/Documents/git/Kaboom/custom-object-language/CustomProgrammingLanguage/bin -l main test.c -o "KaboomTest"

问题是g ++打印出错误:

test.c: In function ‘int main()’:
test.c:4: warning: deprecated conversion from string constant to ‘char*’
/tmp/ccF7XCBs.o: In function `main':
test.c:(.text+0x19): undefined reference to `initLabel(char*, LabelClassType)'
collect2: ld returned 1 exit status

真正的问题是,如果我使用gcc编译test.c,程序就可以正常工作:

gcc -I /home/koldar/Documents/git/Kaboom/custom-object-language/CustomProgrammingLanguage/include/ -I /home/koldar/Documents/git/Kaboom/custom-object-language/KaboomTest/cute/ -L /media/Dati/Users/Koldar/Documents/git/Kaboom/custom-object-language/CustomProgrammingLanguage/bin -l main test.c -o "KaboomTest"
koldar@Octav:~/Documents/git/Kaboom/custom-object-language/KaboomTest$ ./KaboomTest
OK.
koldar@Octav:~/Documents/git/Kaboom/custom-object-language/KaboomTest$ 

现在我很确定我可以在g ++编译的程序中链接gcc编译的共享库,但是我该怎么做呢?谢谢你的回答,抱歉我的英文不好

1 个答案:

答案 0 :(得分:7)

extern "C"
{
#include "Label.h"
}

喜欢这个。