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

Optimize source structure for C++ projects

本文关键字:c++ 项目 结构 源代码 优化      更新时间:2023-10-16

我想创建一个小项目,它分为多个文件。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:

#ifndef "sc.hpp"
#define sc_hpp
int add(int a, int b);

#endif

function.cpp:

#include "sc.hpp"
int add(int a, int b)
{
    return(a + b);
}

但是它不起作用。错误:

`add' undeclared (first use this function) 

我第一次尝试在多个文件中制作程序,所以我认为这个问题一定很容易解决。

你有两个明显的错误:

在你的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:

    // 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

关于如何组织代码文件的更多信息,请点击这里。

一般来说,预处理器指令#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[])
   {
   }