2016-05-31 5 views
0

私は、補足的な追加ソースコードファイル(異なる人が多少異なる機能を追加する可能性がある)に応じて、異なる動作をするプログラムを作成します。ソースコードファイルセットに応じたC++プログラムの動作

file1.cpp:

#include <iostream> 
#include <string.h> 
using namespace std; 

class base { 
    public: 
    void ausgeb() { cout<<"here output base"<<endl; } 
}; 

class derive: public base; 

int main(int argc, char** argv) 
{ 
    derive beisp; 
    beisp.ausgeb(); 
} 

file2.cpp:今、私はそれを望んだ

#include <iostream> 
    #include <string.h> 
    using namespace std; 
    class base; 
    class derive : public base 
    { 
    public: 
    void ausgeb() { cout<<"here output derive"<<endl; } 
    }; 

私は(非コンパイル)次のコードに似た関数のオーバーロード、考えました
g++ -o o1 file1.cpp file2.cpp 

および

g++ -o o2 file1.cpp 

は、出力が異なる実行可能ファイルを生成する必要があります。 その必要性を満たす可能性がありますか?

+0

'file2.cpp'では、コンストラクタが[pimpl](https://en.wikipedia.org/wiki/Opaque_pointer#C)を使って' derive'の実装を切り替えるオブジェクトをファイルスコープに持つことができます。 2B.2B)イディオム。 –

答えて

2

このソリューションを使用すると、コンパイラを切り替えた場合、それはおそらく...これ以上は動作しません、GCC固有のものです

file1.cpp:

#include <iostream> 

void printOut() __attribute__((weak)); 
void printOut() 
{ 
    ::std::cout << "weak" << ::std::endl; 
} 

int main(int, char*[]) 
{ 
    printOut(); 
    return 0; 
} 

file2.cpp:

#include <iostream> 

void printOut() 
{ 
    ::std::cout << "strong" << ::std::endl; 
} 

より高度な(除外プリントアウト実装):

file1.h:

class Base 
{ 
    virtual void printOut(); 
} 

file1.cpp

#include "file1.h" 
Base& getInstance() __attribute__((weak)); 
Base& getInstance() 
{ 
    static Base theInstance; 
    return theInstance; 
} 

int main(int, char*[]) 
{ 
    Base& instance = getInstance(); 
    instance.printOut(); 
} 

file2.cpp:

file1.h:

class Base 
{ 
    virtual void printOut(); 
} 
プリプロセッサシンボルを定義介し

#include "file1.h" 
class Derived : public Base 
{ 
    virtual void printOut(); 
} 

Base& getInstance() 
{ 
    static Derived theInstance; 
    return theInstance; 
} 

はより一般的な解決策、

file1.cpp

#include "file1.h" 
#ifdef USE_DERIVED 
#include "file2.h" 
#endif 

void Base::printOut() 
{ 
} 

int main(int, char*[]) 
{ 
#ifdef USE_DERIVED 
    Derived instance; 
#else 
    Base instance; 
#endif 
    instance.printOut(); 
} 

file2.h:

#include "file1.h" 
class Derived : public Base 
{ 
    virtual void printOut(); 
} 

file2.cpp:他方である場合に

g++ file1.cpp
g++ -DUSE_DERIVED file1.cpp file2.cpp

void Derived::printOut() 
{ 
} 

とコンパイル。

関連する問題