This is the source code of the file:
fileselector.h:
#ifndef FILE_SELECTOR
#define FILE_SELECTOR
const char *open_file_dialog();
const char *save_file_dialog();
#endif
linux/fileselector.cpp:
#include <cstring>
#include "../fileselector.h"
#include <iostream>
const char *open_file_dialog() {
...
}
const char *save_file_dialog() {
...
}
This is my static library production steps:
$ gcc linux/fileselector.cpp fileselector.h -c
$ ar rs libfileselector.a fileselector.o
This is a test using a static library:
main.c
#include "fileselector.h"
int main() {
open_file_dialog();
return 0;
}
$ gcc main.c -L. -lfileselector -o main
/usr/bin/ld: /tmp/ccOTrMR8.o: in function `main':
main.c:(.text 0xa): undefined reference to `open_file_dialog'
collect2: error:ld return 1
Where is the problem?
CodePudding user response:
You defined a set of C functions but are using them from a C program.
Function names in C are mangled during the compilation phase to allow for multiple functions with the same name but different signatures to exist. C programs don't do name mangling, so the compiled name of the library functions don't match the plain function name that the C program expects.
If you want C functions to be usable by a C program, you need to disable name mangling by adding extern "C"
around the definitions and declarations.
So your C source file would look like this:
extern "C" {
const char *open_file_dialog() {
...
}
const char *save_file_dialog() {
...
}
}
And your header would look like this:
#ifdef __cplusplus
extern "C" {
#endif
const char *open_file_dialog();
const char *save_file_dialog();
#ifdef __cplusplus
}
#endif
The #ifdef
's in the header are needed because extern "C"
is a C only feature.
Also, it's not necessary to list the header file when compiling. Because it is included in the source file it is already being compiled.