C ++如何正确使用#include?

时间:2014-01-28 14:02:07

标签: c++ header active-directory include

我想在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;
        }
    }
}

4 个答案:

答案 0 :(得分:2)

在项目的属性页面中,将'printstuff.h'的路径放在'Additional Include Directories'中。通过这样做,您可以通过#include <printstuff.h>

使用头文件

所以,假设'some.h'文件路径在'C:\ ref \ include'中,你的项目路径在'C:\ Projects'中。

  • 如果您将“C:\ ref \ include”的路径放在“其他包含目录”中,则可以使用#include <some.h>
  • 如果您不放置路径,则必须使用相对路径,例如#include "..\ref\include\some.h"

答案 1 :(得分:1)

您可以通过告诉Visual Studio在哪里搜索包含指令来实现此目的。

要执行此操作右键单击“解决方案资源管理器”中的“项目”并选择“属性”。

在属性中编辑配置属性&gt;包含指令。添加放置Header文件的目录。

检查快照。 Image Showing Include Directive Customization Option

答案 2 :(得分:0)

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

答案 3 :(得分:0)

如果您只是想添加printstuff.h,请在项目的include属性中添加您的目录: 右键单击您的项目 - &gt;属性 - &gt; C / C ++ - &gt;一般 - &gt; Additionnal包括目录

然后添加你的目录,只需#include你的标题;)