C/C++編譯

  1. sample2.cpp
#include "sample2.h"
#include <string.h>

//克隆一個0-terminated C string, 用new分配內存.
const char* MyString::CloneCString(const char* a_c_string) {
    if (a_c_string == NULL) return NULL;

    const size_t len = strlen(a_c_string);
    char* const clone = new char[ len + 1 ];
    memcpy(clone, a_c_string, len + 1);

    return clone;
}

void MyString::Set(const char* a_c_string) {
    // Makes sure this works when c_string == c_string_
    const char* const temp = MyString::CloneCString(a_c_string);
    delete[] c_string_;
    c_string_ = temp;
}
  1. sample2.h
#ifndef GTEST_SAMPLE2_H_
#define GTEST_SAMPLE2_H_

#include <string.h>
// 一個簡單的string類.
class MyString {
private:
    const char* c_string_;
    const MyString& operator=(const MyString& rhs);
public:
    static const char* CloneCString(const char* a_c_string);
    MyString() : c_string_(NULL) {}
    explicit MyString(const char* a_c_string) : c_string_(NULL) {
        Set(a_c_string);
    }
    MyString(const MyString& string) : c_string_(NULL) {
        Set(string.c_string_);
    }
    ~MyString() { delete[] c_string_; }
    const char* c_string() const { return c_string_; }
    size_t Length() const {
        return c_string_ == NULL ? 0 : strlen(c_string_);
    }
    void Set(const char* c_string);
};

#endif  // GTEST_SAMPLE2_H_
  1. main.cpp
#include "sample2.h"
#include "gtest/gtest.h"

// 本例用於測試MyString

// 測試默認構造函數
TEST(MyString, DefaultConstructor) {
const MyString s;

EXPECT_STREQ(NULL, s.c_string());
EXPECT_EQ(0u, s.Length());
}

const char kHelloString[] = "Hello, world!";

//測試帶一個c string的構造函數
TEST(MyString, ConstructorFromCString) {
const MyString s(kHelloString);
EXPECT_TRUE(strcmp(s.c_string(), kHelloString) == 0);
EXPECT_EQ(sizeof(kHelloString)/sizeof(kHelloString[0]) - 1,
s.Length());
}

// 測試拷貝構造函數
TEST(MyString, CopyConstructor) {
const MyString s1(kHelloString);
const MyString s2 = s1;
EXPECT_TRUE(strcmp(s2.c_string(), kHelloString) == 0);
}

// 測試Set方法
TEST(MyString, Set) {
MyString s;

s.Set(kHelloString);
EXPECT_TRUE(strcmp(s.c_string(), kHelloString) == 0);

// 當Set方法的參數與MyString中的c string 指針相同時,設定依然有作用
s.Set(s.c_string());
EXPECT_TRUE(strcmp(s.c_string(), kHelloString) == 0);

// Can we set the MyString to NULL?
s.Set(NULL);
EXPECT_STREQ(NULL, s.c_string());
}

int main(int argc, char *argv[])
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

  1. g++ sample2.cpp -shared -fPIC -o sample2.o
  2. g++ -o m main.cpp -lgtest -lpthread ./sample2.o -I .
  1. 函數在.h文件中聲明解決編譯通過問題,用於解決動態庫共享留下的問題,問題由動態庫共享所產生(criterion != correct)。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章