From 50f10338c2da673528c25b5cd6d7c91f08d182b3 Mon Sep 17 00:00:00 2001 From: Jakob Kaivo Date: Thu, 8 Sep 2022 19:46:25 -0400 Subject: add logic for finding -Ldirectories and -llibraries --- cc.c | 2 -- libs.c | 39 +++++++++++++++++++++++++++++---------- 2 files changed, 29 insertions(+), 12 deletions(-) diff --git a/cc.c b/cc.c index 409ec2f..cb07fa9 100644 --- a/cc.c +++ b/cc.c @@ -96,8 +96,6 @@ int main(int argc, char *argv[]) struct macro *predef = do_predefs(argv[0]); - addlibdir("/lib/x86_64-linux-gnu", 0); - for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "-c")) { output = OBJECT; diff --git a/libs.c b/libs.c index e9ad7ae..c5272e3 100644 --- a/libs.c +++ b/libs.c @@ -11,29 +11,48 @@ #include "cc.h" #include "libs.h" -static char **libdirs = NULL; -static size_t nlibdirs = 0; + +static char *system_dirs[] = { + "/lib/x86_64-linux-gnu", + "/usr/lib/x86_64-linux-gnu", + "/usr/local/lib/x86_64-linux-gnu", +}; +static size_t nsystem_dirs = sizeof(system_dirs) / sizeof(system_dirs[0]); + +static char **user_dirs = NULL; +static size_t nuser_dirs = 0; void addlibdir(char *path, int commandline) { - libdirs = realloc(libdirs, (nlibdirs + 1) * sizeof(*libdirs)); - if (!libdirs) { + user_dirs = realloc(user_dirs, (nuser_dirs + 1) * sizeof(*user_dirs)); + if (!user_dirs) { error(NULL, commandline, "out of memory adding '%s' to library search path\n", path); } - libdirs[nlibdirs++] = path; + user_dirs[nuser_dirs++] = path; } -char *findlib(const char *lib) +static char *do_findlib(size_t ndirs, char *dirs[static ndirs], size_t plen, char path[static plen], const char *lib) { - char path[PATH_MAX]; - for (size_t i = 0; i < nlibdirs; i++) { - snprintf(path, sizeof(path), "-l%s/lib%s.a", libdirs[i], lib); + for (size_t i = 0; i < ndirs; i++) { + snprintf(path, plen, "-l%s/lib%s.a", dirs[i], lib); printf("checking %s\n", path + 2); if (access(path + 2, F_OK) == 0) { printf("\tOK\n"); - return strdup(path); + return path; } } + return NULL; +} + +char *findlib(const char *lib) +{ + static char path[PATH_MAX]; + if (do_findlib(nsystem_dirs, system_dirs, sizeof(path), path, lib)) { + return path; + } + if (do_findlib(nuser_dirs, user_dirs, sizeof(path), path, lib)) { + return path; + } error(NULL, 1, "could not find library -l%s\n", lib); return NULL; } -- cgit v1.2.1