Skip to content

Commit

Permalink
llcppcfg: libs -L path support in ubuntu
Browse files Browse the repository at this point in the history
  • Loading branch information
tsingbx committed Jan 4, 2025
1 parent 94a366d commit 6c6d1f5
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
11 changes: 11 additions & 0 deletions cmd/llcppcfg/llcppgcfg/cfg.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strings"
"unicode"
Expand Down Expand Up @@ -408,6 +409,16 @@ func GenCfg(name string, cpp bool, expand CfgMode, exts []string) (*bytes.Buffer

cfg.Name = NormalizePackageName(cfg.Name)

if runtime.GOOS == "linux" {
libpath, _ := SearchLib(name)
if len(libpath) > 0 {
libs, err := CmdOutString(ExecCommand("pkg-config", "--libs", name), "")
if err == nil {
cfg.Libs = fmt.Sprintf("-L%s %s", libpath, strings.TrimSpace(libs))
}
}
}

buf := bytes.NewBuffer([]byte{})
jsonEncoder := json.NewEncoder(buf)
jsonEncoder.SetIndent("", "\t")
Expand Down
73 changes: 73 additions & 0 deletions cmd/llcppcfg/llcppgcfg/llcpplibpath.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package llcppgcfg

import (
"fmt"
"io"
"log"
"runtime"
"strings"
)

const LINUX = "linux"

func IsLibInDir(dir string, lib string) bool {
if runtime.GOOS != LINUX {
return false
}
cmd := ExecCommand("find", dir, "-name", lib+".so*")
out, err := CmdOutString(cmd, "")
if err != nil {
return false
}
if out == "" {
return false
}
return strings.Contains(out, lib)
}

func SearchLib(lib string) (string, error) {
if runtime.GOOS != LINUX {
return "", fmt.Errorf("only support linux")
}
ldCmd := ExecCommand("ld", "--verbose")
ldRes, err := CmdOutString(ldCmd, "")
if err != nil {
log.Fatal(err)
}
cmd := ExecCommand("grep", "SEARCH_DIR")
stdin, err := cmd.StdinPipe()
if err != nil {
log.Fatal(err)
}
go func() {
defer stdin.Close()
_, wrErr := io.WriteString(stdin, ldRes)
panic(wrErr)
}()
out, err := cmd.CombinedOutput()
if err != nil {
log.Fatal(err)
}
searchDirs := strings.Split(string(out), ";")
libs := ""
findDirs := make([]string, 0, len(searchDirs))
for _, searchDir := range searchDirs {
eqIndex := strings.Index(searchDir, "=")
endQuoteIndex := strings.LastIndex(searchDir, "\"")
if eqIndex != -1 && endQuoteIndex != -1 {
dir := searchDir[eqIndex+1 : endQuoteIndex]
if IsLibInDir(dir, lib) {
findDirs = append(findDirs, dir)
}
}
}
maxDir := 0
for _, dir := range findDirs {
cnt := strings.Count(dir, "/")
if cnt > maxDir {
maxDir = cnt
libs = dir
}
}
return libs, nil
}

0 comments on commit 6c6d1f5

Please sign in to comment.