2013-07-22 226 views
0

我是C++ noob,現在擺弄了幾個小時的下列問題。希望有人能夠啓發我。如何將字符串類型參數傳遞給C++方法

我有內容,像這樣一個CPP文件:

TEST.CPP文件內容

#include <iostream> 
#include <exception> 
#include <stdlib.h> 
#include <string.h> 
using std::cin; using std::endl; 
using std::string; 


string foobar(string bar) { 
    return "foo" + bar; 
} 

int main(int argc, char* argv[]) 
{ 
    string bar = "bar"; 
    System::convCout << "Foobar: " << foobar(bar) << endl; 
} 

這一個編譯和運行良好。現在,我想放在foobar的到外部庫:

mylib.h文件內容

string foobar(string bar); 

mylib.cpp文件內容

#include <string.h> 
using std::cin; using std::endl; 
using std::string; 

string foobar(string bar) { 
    return "foo" + bar; 
} 

TEST.CPP文件內容

#include <iostream> 
#include <exception> 
#include <stdlib.h> 
#include "mylib.h" 

int main(int argc, char* argv[]) 
{ 
    string bar = "bar"; 
    System::convCout << "Foobar: " << foobar(bar) << endl; 
} 

我調整了我的Makefile,以便test.cpp編譯並鏈接mylib,但我總是遇到錯誤:

test.cpp::8 undefined reference to `foobar(std::string) 

我該如何處理字符串參數?我的嘗試似乎在這裏完全錯誤。

問候 菲利克斯

+1

顯示完整的鏈接聲明。 – trojanfoe

+0

你是如何與外部圖書館聯繫的?你忘了添加'-lmylib'來鏈接參數嗎? –

+1

你的意思是包括''而不是''? –

回答

1

C++標準庫類型std::string是在頭string。要使用它,您必須包含<string>,而不是<string.h>。你mylib.h應該是這個樣子

#ifndef MYLIB_H 
#define MYLIB_H 

#include <string> 

std::string foobar(std::string bar); 

#endif 

和你mylib.cpp應該包括它:

#include "mylib.h" 

std::string foobar(std::string bar) { 
    return "foo" + bar; 
} 

注意,這可能是不必要的按值傳遞bar。看看你的代碼,const參考可能會。

+0

謝謝!瞭解。這效果很好,並在我的調試文件夾中生成一個mylib.o。當我嘗試通過ruby ffi(即目標)加載該目標文件時,出現錯誤:只能加載ET_DYN和ET_EXEC。我猜,我的mylib.o文件不是可以由其他進程動態加載的共享對象。但我如何實現這一目標? – GeorgieF

+0

@GeorgieF真的取決於你的平臺。您應該查看如何在該平臺上構建共享庫,以及如何使用ruby ffi(我沒有經驗)使用它。 – juanchopanza

+0

感謝您的意見。不幸的是,我有一堆預裝的代碼,必須將其一些功能提取到一個庫中。 Makefile已經存在,我試圖通過'arrvs foobar.a foobar.o'和'ar crf foobar.so foobar.o'創建一個.a和.so文件。結果不能由ffi加載。由於我沒有GUI IDE,我可以從模板中創建新的東西,所以我在這裏堅持使用它。無論如何。 – GeorgieF

相關問題