duck
duck

Reputation: 47

How to use my static library (.a) in swift 3

I want to buid and use static library (.a) in swift 3. example: i build a lib helloLib.a, and use it.

hello.c

#include <stdio.h>
#include "hello.h"
int printHello()
{
    printf("hello wourl");
    return 0;
}

hello.h

#include <stdio.h>
int printHello();

build to: libHello.a and copy to /usr/local/lib

Code swift

module.modulemap

module hello [system] {
    header "hello.h"
    link "libhello"
    export *
}

Package.swift

import PackageDescription
let package = Package(
    name: "hello",
    dependencies: []
)

use module hello

main.swift

import hello

printHello()

build with swift (command): swift build

get an error:

Compile Swift Module 'usehello' (1 sources)

Linking ./.build/debug/usehello

ld: library not found for -llibhello for architecture x86_64

:0: error: link command failed with exit code 1 (use -v to see invocation)

:0: error: build had 1 command failures

Upvotes: 3

Views: 2398

Answers (2)

Anatoli P
Anatoli P

Reputation: 4891

I think you have omitted a lot of information about what you did, which makes it difficult to provide an answer with certainty. Did you do something along the lines of https://github.com/apple/swift-package-manager/blob/master/Documentation/Usage.md? What is your directory structure? Where is hello.h?

Anyway, judging from the error message, one problem is that you use

   link "libhello"

in module.modulemap. It is unclear what the name of the static library is. It cannot be called helloLib.a, its name must start with lib. If it is called libhelloLib.a, then in the module map it must be

link "helloLib"

You may also want to add the -Xlinker -L/usr/local/lib option as suggested in another answer.

Hope this helps.

Upvotes: 1

Robert F. Dickerson
Robert F. Dickerson

Reputation: 483

I think it's not finding your static library in /usr/local/lib. You should build with compiler flags such as:

swift build -Xcc -I/usr/local/include -Xlinker -L/usr/local/lib

Upvotes: 0

Related Questions