简体   繁体   English

优化C ++项目的源代码结构

[英]Optimize source structure for C++ projects

I would like to create a little project, which is divided in more then one file. 我想创建一个小项目,将其分成多个文件。 main.cpp: main.cpp:

#include <cstdlib>
#include <iostream>
#include sc_hpp

using namespace std;

int main(int argc, char *argv[])
{
    add(3,4);
    system("PAUSE");
    return EXIT_SUCCESS;
}

sc.hpp: sc.hpp:

#ifndef "sc.hpp"
#define sc_hpp

int add(int a, int b);



#endif

function.cpp: function.cpp:

#include "sc.hpp"

int add(int a, int b)
{
    return(a + b);
}

But it doesn't work. 但这是行不通的。 ERROR: 错误:

`add' undeclared (first use this function) 

First time I'm trying make programme in more then one file, so I think the problem must be easy to solve. 第一次尝试使程序包含多个文件,因此我认为该问题必须易于解决。

You have two obvious mistakes: 您有两个明显的错误:

In your main : 在您的main

     #include <cstdlib>
     #include <iostream>
     // the included header file needs to be enclosed in " " 
     // and it needs a suffix, i.e.: `.h`
     #include "sc_hpp.h"

     using namespace std;

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

     } 

In sc.hpp: sc.hpp:

    // the include guards doesn't have to be enclosed in " "
    // the suffix's dot:'.' is replaced with underscore: '_'
    // header name in uppercase letters
    #ifndef SC_HPP_H
    #define SC_HPP_H

    int add(int a, int b);

    //  included .cpp files with function implementation here
    #include "sc.hpp"

    #endif

More on how to organize code files, here . 有关如何组织代码文件的更多信息,请点击此处

In general the preprocessor directive #include expands the code contained in the file that follows it, so your code in main looks like this: 通常,预处理程序指令#include会扩展紧随#include的文件中包含的代码,因此main的代码如下所示:

   #include <cstdlib>
   #include <iostream>
   // #include "sc_hpp.h" replaced with
   int add(int a, int b);
   // the #include "sc.cpp" nested within the "sc_hpp.h" is replaced with
   int add(int a, int b)
   {
       return(a + b);
   }

   using namespace std;

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

   } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM