C 如何正确使用#include

C++ how to properly use #include?

本文关键字:#include 何正确      更新时间:2023-10-16

我想在我的main.cpp程序中包含printstuff.h。我遇到了没有这样的文件或目录错误。我不想将整个目录带有双重报价。我只想简单地放置printStuff.h如何完成此操作?

我正在使用Visual Studio 2012。

main.cpp

#include<iostream>
#include<cstdlib>
#include<printstuff.h>
using namespace std;
inline void swap( int *x, int *y ) {
    int *z = x;
    *x = *y;
    *y = *z;
}
int main( ) {
    /*int x = 0, y = 1;
    swap( x, y );
    cout << x << endl << y << endl;*/
    printStuff( );
    system( "pause" );
    return 0;
}

printstuff.h

#include<iostream>
using namespace std;
void printStuff( );
void printStuff( ) {
    int count[ ] = { 1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 };
    char symb[ ] = "abcdefghijk";
    for ( int j = 1; j < 12; j++ ) {
        char c = symb[ j ];
        for ( int i = 0; i < 11; i++ ) {
            int times = count[ i ];
            while ( times != 0 ) {
                cout << c;
                times--;
            }
            cout << endl;
        }
    }
}

在项目的属性页面中,将'printStuff.h'的路径放在'其他包含目录'中。这样,您可以通过#include <printstuff.h>

使用标头文件

所以,假设" some.h"文件路径在'c: ref include'中,您的项目路径在'c: projection'中。

  • 如果将" C: ref include"的路径放在"附加目录"中,则可以使用#include <some.h>
  • 如果您不采用路径,则必须使用相对路径,例如#include "..refincludesome.h"

您可以通过告诉Visual Studio在哪里搜索包括指令。

要右键单击解决方案资源管理器的项目,然后选择属性。

在属性中编辑配置属性>包括指令。添加您的目录放置标题文件的位置。

查看快照。显示的图像包括指令定制选项

//printstuff.h

#ifndef ADD_H_INCLUDED
#define ADD_H_INCLUDED
void printStuff( );
#endif

//printstuff.cpp

#include<printstuff.h>
void printStuff( ) {
int count[ ] = { 1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 };
char symb[ ] = "abcdefghijk";
for ( int j = 1; j < 12; j++ ) {
    char c = symb[ j ];
    for ( int i = 0; i < 11; i++ ) {
        int times = count[ i ];
        while ( times != 0 ) {
            cout << c;
            times--;
        }
        cout << endl;
    }
}
}

//main.cpp

#include <iostream>
#include <cstdlib>
#include <printstuff.h>
using namespace std;
inline void swap( int *x, int *y ) {
int *z = x;
*x = *y;
*y = *z;
}
int main( ) {
/*int x = 0, y = 1;
swap( x, y );
cout << x << endl << y << endl;*/
printStuff( );
system("PAUSE");
return 0;
}

如果您只想添加printstuff.h添加您的目录中的目录:右键单击您的项目 ->属性 -> c/c ->常规 ->添加includnal include directory

然后添加您的目录,然后#include header;)