0

I'm using 64-bit CentOS version of Linux. I'm trying to create and use a static library (libUtility.a) in my C and C++ programs. I can compile the library with C, and produce the libUtility.a file with ar. Then I try to link it into my program. Everything works when I use the C compiler

cc myprog.c -o myprog -I/usr/local/include -L/LocationOfMyLib -lUtility

However, when I use the g++ compiler, I receive the errors.

g++ myprog.c -o myprog -I/usr/local/include -L/LocationOfMyLib -lUtility
myprog.c: In function 'int main(int, char**)':
/tmp/cckIN1Yk.o: In function `main':
myprog.c:(.text+0x41): undefined reference to `Utility_HiWorld(char*)'
collect2: ld returned 1 exit status

I have moderate experience in C and C++, but no experience creating my own libraries. This library only has one subroutine named Utility_HiWorld(). And myprog.c only calls that one subroutine. What am I doing wrong in here?

NEW: Okay, I definitely didn't use 'extern "C"'. I didn't even know what that was. That solved it.

JB_User
  • 3,117
  • 7
  • 31
  • 51

1 Answers1

4

I would guess that you are failed to tell your C++ compiler that the external function is written in C.

Since you want to use the library from C and C++ you need to do something like this in your libraries header file.

#ifdef __cplusplus
extern "C" {
#endif

void Utility_HiWorld(char*);

#ifdef __cplusplus
}
#endif

__cplusplus is only defined for a C++ programs, so a C++ program will see extern "C" { ... } which is what it needs to tell it that Utility_HiWorld is a C function.

See here for more details.

Just a guess, post some code if you think the problem is something else.

Community
  • 1
  • 1
john
  • 85,011
  • 4
  • 57
  • 81