undefined reference to `android::Mutex::lock()'
转自http://blog.csdn.net/keensword007/article/details/5720636
用NDK编译时出现这么个错误undefined reference to `android::Mutex::lock()'
起初以为没有链接必要的so,结果加上了 -lutils 也不行。所以google 了一下,发现有人遇到过此问题,如下:
察看了一下ndk中的STABLE-APIS.TXT文档,上面有这样一句:
Note that the Android C library includes support for pthread (<pthread.h>),
so "LOCAL_LIBS := -lpthread" is not needed. The same is true for real-time
extensions (-lrt on typical Linux distributions).
也就是说使用多线程,并不需要增加-lpthread编译选项,看来解决问题还需要从源代码入手。察看frameworks/base/include/utils/threads.h文件,关于Mutex有如下代码片断:
#if defined(HAVE_PTHREADS)
inline Mutex::Mutex() {
pthread_mutex_init(&mMutex, NULL);
}
inline Mutex::Mutex(const char* name) {
pthread_mutex_init(&mMutex, NULL);
}
inline Mutex::Mutex(int type, const char* name) {
if (type == SHARED) {
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&mMutex, &attr);
pthread_mutexattr_destroy(&attr);
} else {
pthread_mutex_init(&mMutex, NULL);
}
}
inline Mutex::~Mutex() {
pthread_mutex_destroy(&mMutex);
}
inline status_t Mutex::lock() {
return -pthread_mutex_lock(&mMutex);
}
inline void Mutex::unlock() {
pthread_mutex_unlock(&mMutex);
}
inline status_t Mutex::tryLock() {
return -pthread_mutex_trylock(&mMutex);
}
#endif // HAVE_PTHREADS
#if defined(HAVE_PTHREADS)// implemented as inlines in threads.h#elif defined(HAVE_WIN32_THREADS)Mutex::Mutex(){HANDLE hMutex;assert(sizeof(hMutex) == sizeof(mState));hMutex = CreateMutex(NULL, FALSE, NULL);mState = (void*) hMutex;}Mutex::Mutex(const char* name){// XXX: name not used for nowHANDLE hMutex;assert(sizeof(hMutex) == sizeof(mState));hMutex = CreateMutex(NULL, FALSE, NULL);mState = (void*) hMutex;}Mutex::Mutex(int type, const char* name){// XXX: type and name not used for nowHANDLE hMutex;assert(sizeof(hMutex) == sizeof(mState));hMutex = CreateMutex(NULL, FALSE, NULL);mState = (void*) hMutex;}Mutex::~Mutex(){CloseHandle((HANDLE) mState);}status_t Mutex::lock(){DWORD dwWaitResult;dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;}void Mutex::unlock(){if (!ReleaseMutex((HANDLE) mState))LOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex/n");}status_t Mutex::tryLock(){DWORD dwWaitResult;dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)LOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex/n");return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;}#else#error "Somebody forgot to implement threads for this platform."#endif
LOCAL_CXXFLAGS := -DHAVE_PTHREADS