如何使用mingw从另一个文件中存在的main方法运行文件中存在的方法

时间:2014-12-18 15:40:42

标签: c netbeans mingw

我已经在netbeans上安装了mingw用于C编程 然后我创建了一个文件" Myfile.c",我在其中创建了一个方法callme()
但是这个文件不包含main方法 我想从另一个包含main方法的文件中调用callme()

myfile.c文件

#include <stdio.h>
void callme() {
    printf("I am called");
}

EntryFile.c

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {
    // How to call callme() from here OR use this method anyhow.
    return (EXIT_SUCCESS);
}

出于某些原因,我不想在Myfile.c中创建主要方法。

被修改

myfile.c文件

#include <stdio.h>
void callme();
void callme() {
    printf("I am called");
}

EntryFile.c

#include <stdio.h>

int main(int argc, char** argv) {
    callme();
}

错误

"/C/MinGW/MSYS/1.0/bin/make.exe" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf
make.exe[1]: Entering directory `/c/Users/Afzalex/Documents/NetBeansProjects/CppStoreRoom'
"/C/MinGW/MSYS/1.0/bin/make.exe"  -f nbproject/Makefile-Debug.mk dist/Debug/MinGW-Windows/cppstoreroom.exe
make.exe[2]: Entering directory `/c/Users/Afzalex/Documents/NetBeansProjects/CppStoreRoom'
mkdir -p build/Debug/MinGW-Windows
rm -f "build/Debug/MinGW-Windows/Myfile.o.d"
gcc    -c -g -MMD -MP -MF "build/Debug/MinGW-Windows/Myfile.o.d" -o build/Debug/MinGW-Windows/Myfile.o Myfile.c
make.exe[2]: *** No rule to make target `newmain.cpp', needed by `build/Debug/MinGW-Windows/newmain.o'.  Stop.
make.exe[2]: Leaving directory `/c/Users/Afzalex/Documents/NetBeansProjects/CppStoreRoom'
make.exe[1]: *** [.build-conf] Error 2
make.exe[1]: Leaving directory `/c/Users/Afzalex/Documents/NetBeansProjects/CppStoreRoom'
make.exe": *** [.build-impl] Error 2

2 个答案:

答案 0 :(得分:6)

正如@LPs在他的回答中指出的那样,你应该创建一个包含内容的文件MyFile.h

/* include guards (research the term if you don't know it) */
#ifndef MYFILE_H 
#define MYFILE_H

void callme(void);

#endif // MYFILE_H

并使用

包含EntryFile.c中的此文件
#include "MyFile.h"

或者,您可以使用

将原型直接写入EntryFile.c
extern void callme(void);

在使用该函数之前的全局范围。这两种方式都会使编译器知道该函数,您可以在main函数中使用它。

答案 1 :(得分:4)

创建一个MyFile.h,您将在其中写下:

extern void callme();

然后在EntryFile.c中添加

#include "MyFile.h"

然后你可以在main方法中调用callme