Reputation: 277
I often see __declspec(dllexport)
/ __declspec(dllimport)
instructions on Windows, and __attribute__((visibility("default")))
on Linux with functions, but I don't know why. Could you explain to me, why do I need to use theses instructions for shared libraries?
Upvotes: 0
Views: 1390
Reputation:
The Windows-exclusive __declspec(dllexport)
is used when you need to call a function from a Dll (by exporting it) , that can be accessed from an application.
Example This is a dll called "fun.dll" :
// Dll.h :
#include <windows.h>
extern "C" {
__declspec(dllexport) int fun(int a); // Function "fun" is the function that will be exported
}
// Dll.cpp :
#include "Dll.h"
int fun(int a){
return a + 1;
}
You can now access the "fun" from "fun.dll" from any application :
#include <windows.h>
typedef int (fun)(int a); // Defining function pointer type
int call_fun(int a){
int result = 0;
HMODULE fundll = LoadLibrary("fun.dll"); // Calling into the dll
if(fundll){
fun* call_fun = (fun*) GetProcAddress(fundll, "fun"); // Getting exported function
if(call_fun){
result = call_fun(a); // Calling the exported fun with function pointer
}
}
return result;
}
Upvotes: 4