2017-11-10 18 views
1

C 파일이 (헤더 파일을 통해) 다른 스크립트에 포함될 수 있는지 궁금해하고 자체적 인 main 함수를 사용하여 독립적으로 실행할 수도 있습니다. 즉, C 파일은 다른 C 스크립트에 기능을 제공하기 위해 포함될 수 있지만 대체 기능을 제공하기 위해 직접 실행될 수도 있습니다.포함 된 C 파일도 직접 실행할 수 있습니까?

예를 들어, 파이썬 스크립트가이를 수행 할 수 있습니다. 다른 파이썬 파일에서이 코드 가져올 수

def functionsToBeImported(): 
    # code to be run by an importing script 
    pass 

if __name__ == '__main__': 
    # code to be run by this script independently 
    pass 

(import ABOVESCRIPT)는 functionsToBeImported에 대한 액세스를 제공하거나, 독립적 if 블록 내의 코드를 실행하는 (python ABOVESCRIPT.py)을 실행한다.

나는 myScript.c를 통해 C에서이 작업을 수행하려고 시도했습니다

#include "myScript.h" 

void functionsToBeImported() { 
} 

int main (int narg, char* varg[]) { 
} 

myScript.h :

#ifndef MY_SCRIPT_H_ 
#define MY_SCRIPT_H_ 

void functionsToBeImported(); 

#endif // MY_SCRIPT_H_ 

하지만 에 anotherScript.c을이 포함되도록 노력 :

#include "myScript.h" 

int main (int narg, char* varg[]) { 

    functionsToBeImported(); 
} 
,

gcc -std=c99 -c myScript.c 
gcc -std=c99 -c anotherScript.c 
gcc -std=c99 -o anotherScript anotherScript.o myScript.o -lm 

를 통해 컴파일 시도는 컴파일 오류 나는이 '이중 사용'스크립트를 달성 할 수있는 방법

duplicate symbol _main in: 
    myScript.o 
    anotherScript.o 

수 있습니다?

+1

모두를 다룰 수있는 main()이 하나 있습니다. –

+0

나는 당신이 말하는 내용을 복제하고 아래에서 내 대답을 편집하는 방법을 생각했습니다. –

답변

1

당신은 모두 anotherScript.omyScript.o를 링크 할 수있는 곳이 포함되어야합니다,하지만 당신은 같은 것을 할 수있는 : 실제로 같은 것들을 보았다

#define main ignored_main 
// Include myScript.c, not myScript.h 
#include "myScript.c" 
#undef main 

int main (int narg, char* varg[]) { 

    functionsToBeImported(); 
} 

을 비록이 스타일을 추천 할 수는 없지만 (이것은 때때로 유혹적인 지름길이기도하지만) 생산 과정에서 매우 널리 사용되는 코드입니다.

또 다른 옵션은 전 처리기 매크로 (myScript.c에서) 다음과 같이 정의 된 경우에만 main 기능을 포함하는 것입니다 :

#include "myScript.h" 

void functionsToBeImported() { 
} 

#ifdef USE_MAIN 
int main (int narg, char* varg[]) { 
} 
#endif // USE_MAIN 

이것은 파이썬 접근에 정신 유사하다. 하지만 다시 한번이 파일을 별도의 객체 파일로 두 번 컴파일해야합니다.

1

참고 : C 파일은 스크립트가 아닙니다.

C는 절차 언어이므로 한 번에 하나씩해야한다는 점에서 두 가지 주요 기능을 사용할 수 없습니다 (멀티 스레딩이 아닌 경우 한 가지 주요 기능 만 사용할 수 있음).

언제나, 당신이 원하는 것을 복제하는 것에 아주 가깝습니다. 당신이 할 수있는 일은 첫째, 첫 번째 포함 된 파일에서만 main 메소드를 작성하는 것입니다. main 파일에서 atexit() 함수를 C# stdlib.h 파일 (main의 끝에 다른 함수를 호출하는)에서 main2() 함수로 설정합니다 (각 main #() 함수의 프로토 타입이 있는지 확인하십시오 첫 번째 헤더에서도 마찬가지이며 결국 모든 기능을 구현합니다). 원래 MAIN이있는 함수에서 MAIN_ONE이라는 매크로를 정의하십시오. 연속적으로 포함 된 각 파일에서 다음 main을 구현하고 함수가 구현되었는지 확인할 수 있도록 매크로를 만듭니다. 그러나 C에서 프로그램을 만드는 자연스럽고 가장 효율적인 방법은 단지 하나의 주요 기능을 갖는 것입니다.

예 : // 첫 번째 포함 파일 #include // 일부 IDE에는 자동으로 포함됩니다.그것이 이후 atexit() 함수는

#define MAIN_ONE 
void main2(); //For the moment, this is only a prototype. 
void main3(); 
//etc. Until you have created the maximum number of main functions that you can have 
int main() { 
    //do something 
    atexit(main2); // This will execute the function main1() once main returns 
    //All "fake" mains must be void, because atexit() can only receive void functions 
} 

//In second included file 
#if defined(MAIN_THREE) //start from the maximum number of main functions possible 
    #define MAIN_THREE //The define is for preprocessor-checking purposes 
    void main4() { 
     atexit(main5); 
    } 
#elif defined(MAIN_TWO) //start from the maximum number of main functions possible 
    #define MAIN_TWO 
    void main3() { 
     atexit(main5); 
    } 
//Keep repeating until you reach #ifdef(MAIN_ONE) 
#endif 

//At the bottom of the main C file 
//This is done in order to make sure that all functions have actually been created and reside in memory so that an error does not occur 
//(all unused functions are initialized with an empty function here) 
#if defined(MAIN_THREE) //start from the maximum number of main functions possible 
    //Do nothing because if MAIN_THREE is defined when main4(), the last main in my example has already been implemented. 
    //Therefore, no more functions need to be created 
#elif defined(MAIN_TWO) //start from the maximum number of main functions possible 
    #define MAIN_TWO //Since more mains after main2 can be present, another macro for future checks needs to be defined 
    void main3() { 
    } 
//Keep repeating until you reach #ifdef(MAIN_ONE) 
#endif 
+0

첫 단락의 관련성을 이해할 수 없습니다. 제안서에 몇 가지 예제 스 니펫을 제공 할 수 있습니까? –

+0

@Anti Earth 예제를 추가했습니다. –