sun博客

记录点滴!

在这里也搞了好久的时间。总是报以下错。

undefined reference to `numberToByteArray'

其中最重要的是自定义的cpp文件要包含其自定义的头文件。另外cmakelists.txt里面也要把cpp文件添加到add_executable中。(utils.cpp)是自定义头文件的实现。即:

add_executable(testFun test/testFun.cpp
        utils/utils.cpp)

以下为整个文件实例:

//cmakelists.txt
cmake_minimum_required(VERSION 3.26)
project(test)
set(CMAKE_CXX_STANDARD 14)
set(INCLUDE_DIR "/home/cxl/CLionProjects/test/include/")
set(LIBRARY_UNICORN_PATH "/home/cxl/CLionProjects/test/lib/")



# 链接外部库
include_directories(${INCLUDE_DIR})
link_directories(${LIBRARY_UNICORN_PATH})
link_libraries("libunicorn.a" "libcapstone.a")

#[[LINK_LIBRARIES(${UNICORN_INCLUDE_DIR})]]

add_executable(unicornTest unicornTest.c)
add_executable(test test/test.cpp)

add_executable(test_arm64 test/test_arm64.c)
add_executable(testFun test/testFun.cpp
        utils/utils.cpp)
#[[add_executable(unicornTest unicornTest.c)]]



#[[target_link_libraries(test PRIVATE libunicorn.a)]]
target_link_libraries(test PRIVATE -lm pthread)
//utils.h
#ifndef MY_UTILS
#define MY_UTILS

#ifdef __cplusplus
extern "C" {
#endif

#ifdef _MSC_VER
#pragma warning(disable : 4201)
#endif

void pointer2Bytes(void* pointer,  unsigned char* byteArray,char* type);
void reverseByteArray(unsigned char* byteArray, size_t size);
void numberToByteArray(int number, unsigned char* byteArray, size_t size);
#ifdef __cplusplus
}
#endif

#endif

//utils.cpp
// Created by cxl on 10/8/23.
//
#include <cstring>
#include "utils.h"
void reverseByteArray(unsigned char* byteArray, size_t size) {
    size_t start = 0;
    size_t end = size - 1;

    while (start < end) {
        unsigned char temp = byteArray[start];
        byteArray[start] = byteArray[end];
        byteArray[end] = temp;
        start++;
        end--;
    }
}
void pointer2Bytes(void* pointer,  unsigned char* byteArray,char* type) {
    int size=sizeof(pointer);
    memcpy(byteArray, &pointer, size);
    if(strcmp(type,"little") != 0){
        reverseByteArray(byteArray, size);
    }
}
void numberToByteArray(int number, unsigned char* byteArray, size_t size) {
    for (size_t i = 0; i < size; i++) {
        byteArray[i] = static_cast<unsigned char>((number >> (8 * i)) & 0xFF);
    }
}
//testFun.cpp
//
// Created by cxl on 10/8/23.
//
#include "iostream"
#include "utils.h"


using namespace std;


int main() {
    int num = 42;
    int* ptr = &num;
    cout<<ptr<<endl;
    cout<<&ptr<<endl;
    unsigned char byteArray[sizeof(ptr)];
    pointer2Bytes(ptr,byteArray, "little");

    // Print the byte array
    for (size_t i = 0; i < sizeof(ptr); i++) {
        printf("%02x ", byteArray[i]);
    }
    printf("\n");

    return 0;
}

发表评论

邮箱地址不会被公开。 必填项已用*标注