3
votes

I am trying to create a static library in xcode and link to that static library from another program.

So as a test i have created a BSD static C library project and just added the following code:

//Test.h

int testFunction();

//Test.cpp

#include "Test.h"
int testFunction() {
return 12;
}

This compiles fine and create a .a file (libTest.a).

Now i want to use it in another program so I create a new xcode project (cocoa application) Have the following code:

//main.cpp

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

int main (int argc, char * const argv[]) {
    // insert code here...
    std::cout << "Result:\n" <<testFunction();
    return 0;
}

//Testlib.h

extern int testFunction();

I right clicked on the project -> add -> existing framework -> add other Selected the .a file and it added it into the project view.

I always get this linker error:

Build TestUselibrary of project TestUselibrary with configuration Debug

Ld build/Debug/TestUselibrary normal x86_64
cd /Users/myname/location/TestUselibrary
setenv MACOSX_DEPLOYMENT_TARGET 10.6
/Developer/usr/bin/g++-4.2 -arch x86_64 -isysroot /Developer/SDKs/MacOSX10.6.sdk 
-L/Users/myname/location/TestUselibrary/build/Debug  
 -L/Users/myname/location/TestUselibrary/../Test/build/Debug 
-F/Users/myname/location/TestUselibrary/build/Debug 
-filelist /Users/myname/location/TestUselibrary/build/TestUselibrary.build/Debug/TestUselibrary.build/Objects-normal/x86_64/TestUselibrary.LinkFileList 
-mmacosx-version-min=10.6 -lTest -o /Users/myname/location/TestUselibrary/build/Debug/TestUselibrary



Undefined symbols:
  "testFunction()", referenced from:
      _main in main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

I am new to macosx development and fairly new to c++. I am probably missing something fairly obvious, all my experience comes from creating dlls on the windows platform. I really appreciate any help.

2

2 Answers

1
votes

You don't add the library (.a file) as a framework - it's just a library - add it to the project like you would add a source file.

Also note that you don't need Testlib.h - just #include the original Test.h in main.cpp.

1
votes

Are you sure that the libraries source file is named Test.cpp and not Test.c? With .c i get exactly the same error.

If it is Test.c you need to add extern "C" to the header for C++. E.g.:

#ifdef __cplusplus
extern "C" {
#endif

int testFunction();

#ifdef __cplusplus
}
#endif

See e.g. the C++ FAQ lite entry for more details.