2013-06-26 48 views
0

我想从一个“主”文件中的另一个文件包含一个函数。我遵循这种模式:简单的C++函数包含失败

http://www.learncpp.com/cpp-tutorial/18-programs-with-multiple-files/

这里是我的主文件,digispark.cpp:

#include <iostream> 

using namespace std; 

int send(int argc, char **argv); 

int main() 
{ 
    char* on; 
    *on = '1'; 
    char* off; 
    *off = '0'; 
    send(1,&on); 
    return 0; 
} 

这里是我的send.cpp:

#include <stdio.h> 
#include <iostream> 
#include <string.h> 
#if defined WIN 
    #include <lusb0_usb.h> // this is libusb, see http://libusb.sourceforge.net/ 
#else 
    #include <usb.h>  // this is libusb, see http://libusb.sourceforge.net/ 
#endif 

// I've simplified the contents of send for my debugging and your aid, but the 
// complicated arguments are a part of the function that will eventually need 
// to be here. 
int send (int argc, char **argv) 
{ 

    std::cout << "Hello"; 
    return 0; 
} 

我在Ubuntu12.10米编译使用G ++编译器像这样:

g++ digispark.cpp send.cpp -o digispark 

它编译成功。

然而,当我运行程序,“你好”不上来。所以我不相信这个函数被调用。我究竟做错了什么?任何帮助将是伟大的!谢谢!

编辑:

如何处理这个问题:

int send(int argc, char **argv); 

int main() 
{ 
    char* on[4]; 
    on[0] = (char*)"send"; 
    on[1] = (char*)"1"; 
    char* off[4]; 
    off[0] = (char*)"send"; 
    off[1] = (char*)"0"; 
    send(2,on); 
    return 0; 
} 

对于那些你们谁是困惑,为什么我坚持这样做,正如我以前说过,发送功能已建成接受char ** argv(或char * argv [])。我的观点是试图模仿我的主要功能。

这本来是更难以改写,其实云在发送功能采取不同的类型参数不仅仅是在它所想要发送的功能。感谢大家!

因此,如果这有助于任何人试图类似的东西随意使用吧!

+0

不使用文件stdio.h和string.h中,但cstdio并为c_string在C++ – hetepeperfan

+0

这是一个问题与约定或将实际上打破我的计划? – eatonphil

+1

您可能没有准备好使用指针。正如你的代码所显示的那样,它们很难并且很容易被滥用。尽可能地坚持标准的C++库构造。 –

回答

1

你的问题是你不认为这是一个。它在这里:

char* on; 
*on = '1'; 

你宣布char指针,但没有对其进行初始化。然后你解除它。邦,你死了。这就是所谓的未定义行为。一旦你调用U.B.,任何事情都可能发生。如果你幸运的话,那就是崩溃。但我猜你这次没有幸运。

看,如果你想开始在内存中存储的东西,你必须先分配内存。正如hetepeperfan所说,最好的方法就是使用std::string,并让该班负责所有的分配/释放。但是,如果由于某种原因,你认为你必须使用C风格的字符串和指针,那就试试这个:

char on[128]; //or however much room you think you'll need. Don't know? Maybe you shoulda used std::string ... 
*on = '1'; 
*(on+1) = '\0'; //if you're using C-strings, better null terminate. 
char off[128]; 
*off = '0'; 
*(off+1) = '\0'; 
send(1,&on); 
0

好,我觉得你尝试做一些像下面,我试图让它多一点在C++风格,防止使用指针,因为他们不应该在你表现出的代码是必要的。

digispark.cpp

#include "send.h" 

int main (int argc, char** argv){ 

    string on = "1"; 
    string off = "0"; 

    send (on); 
    send (off); 

    return 0; 
} 

send.cpp

#include <iostream> 
#include <string> 

void send(const std::string& s) { 

    std::cout << s << std::endl; 

} 

send.h

void send(const std::string& s); 
+0

对不起,您一定错过了我的评论。指针对于最终进入发送函数的代码是必需的。我现在的问题必须是,我如何将一个char作为char **发送给函数。但这超出了这个特定问题的范围。感谢您的时间。 – eatonphil