I am trying to compile an example program that uses a common library (also developed by me) in C ++, whose name libtestlib.so.
Error
I compiled a shared library without problems, but when I try to compile an executable file that uses this library, I have the following error: iface/libtestlib.so: undefined reference to 'ALIB::function()'
What I've done
I have done the following:
C ++ library (files in $project_dir/lib1):
#ifndef ALIB_H
#define ALIB_H
namespace ALIB{
int function();
}
#endif
-------------------------------------------
#include "alib.h"
using namespace ALIB;
int ALIB::function(){
return 101;
}
C interface for C ++ library (files in $project_dir/iface)
#ifndef IFACE_H
#define IFACE_H
#include "alib.h"
extern "C"{
int IFACE_function();
}
#endif
--------------------------------
#include "iface.h"
int IFACE_function(){
return ALIB::function();
}
--------------------------------------------------------
cmake_minimum_required(VERSION 2.8)
PROJECT( testlib )
include_directories( ../lib1 )
add_library( testlib SHARED iface.cpp )
An executable file that uses the library (files in $project_dir/main):
#include "iface.h"
#include <iostream>
using namespace std;
int main(){
cout << IFACE_function() << endl;
}
-------------------------------------
cmake_minimum_required(VERSION 2.8)
PROJECT( testlib )
find_library( LIB NAMES testlib PATHS ./iface )
include_directories( ./lib1 ./iface )
add_executable( testlib ./main/main.cpp )
target_link_libraries( testlib ${LIB} )
Generated files
$project_dir: all generated by cmake. (CmakeLists.txt, CMakeCache, cmake_install.cmake, MakeFile)
$project_dir/lib1:
alib.cppandalib.h
$project_dir/iface:
iface.cpp, iface.h, libtestlib.so cmake.
$project_dir/main:
main.cpp.
:
$project_dir
├── CMakeCache.txt
├── CMakeFiles
│ ├── ...
├── cmake_install.cmake
├── CMakeLists.txt
├── CMakeLists.txt~
├── iface
│ ├── CMakeCache.txt
│ ├── CMakeFiles
│ │ ├── ...
│ ├── cmake_install.cmake
│ ├── CMakeLists.txt
│ ├── CMakeLists.txt~
│ ├── iface.cpp
│ ├── iface.h
│ ├── libtestlib.so
│ └── Makefile
├── lib1
│ ├── alib.cpp
│ └── alib.h
├── main
│ └── main.cpp
└── Makefile