简体   繁体   中英

Define a C++ class in 2 cpp files?

Can I declare my class in 1 header file and define it in 2 separated cpp files ? (like in C#)
Main reason is for me to reduce the line count of my class definition in the single file I have now. btw all my headers are "include guarded" + "pragma onced".

Header: "foo.h"

#pragma once

#ifndef FOO_H_2014_04_15_0941
#define FOO_H_2014_04_15_0941

class CFoo
{
public:
    int add(int a, int b);
    int sub(int a, int b);
};

#endif

Source: "foo.cpp"

#include "stadafx.h"
#include "foo.h"

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

and "foo2.cpp"

#include "stadafx.h"
#include "foo.h"

int CFoo::sub(int a, int b)
{
    return a - b;
}

When I try I get a compiler error in the second cpp file "cannot open source file stdafx.h" (also "foo.h")

Yes you can do this.

stdafx.h is a precompiled header file. This is a convention of Visual Studio. In order to optimize compilation, often-used headers get put in stdafx.h , then you include this file. The catch is you must put #include "stdafx.h" at the top of your source files.

You can either do that, or disable precompiled header usage for this .cpp file. Or your whole project.

Make sure you use include guards in your foo.h file as well. Either a series of preprocessor directives as @Theolodis has said, or #pragma once .


I agree with @paulm: Splitting up your implementation like this is just an indication that your design is flawed. It's very very rare that this is the "right" decision. Most likely you should consider breaking up your code into smaller, more manageable components.

In the header, add:

#ifndef FOO_H_
#define FOO_H_

class CFoo
{
public:
    int add(int a, int b);
    int sub(int a, int b);
}

#endif

the problem was that your header file has been included twice in the executable, leading to name conflicts. Otherwise everything is fine, you could even take one .cpp file for every method.

Firstly, don't use "include guarded" and "pragma onced" in the same header file! Use "include guarded" only!

Secondly, you must be develop on the windows, may be use visual studio. Because you used the precompiled header file: stdafx.h. And you spell ERROR!

Only this!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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