如何定义在多个 cpp 文件中使用的 interface/API?

How to define an interface/API which is used in multiple cpp files?

我收到以下错误: "Symbol SBPTest multiply defined (by ../../build/typeFind.LPC1768.o and ../../build/main.LPC1768.o)."

我在 common.h 中这样声明了 SBPTest:

#ifndef COMMON_H_
#define COMMON_H_

extern RawSerial SBPTest(USBTX, USBRX);

#endif

其他文件看起来像这样...

typeFind.h:

#include "mbed.h"
#include <string>

extern unsigned int j;
extern unsigned int len;
extern unsigned char myBuf[16];
extern std::string inputStr;

void MyFunc(char* inputBuffer);

typeFind.cpp:

#include "typeFind.h"
#include "common.h"

void MyFunc(char* inputBuffer) {

    inputStr = inputBuffer;

    if (inputStr == "01") {
        len = 16;

        for ( j=0; j<len; j++ )
        {
            myBuf[j] = j;
        }

        for ( j=0; j<len; j++ )
        {
            SBPTest.putc( myBuf[j] );
        }
    }
}

main.cpp:

#include "typeFind.h"
#include "common.h"
#include "stdlib.h"
#include <string>

LocalFileSystem local("local");                 // define local file system 



unsigned char i = 0;
unsigned char inputBuff[32];
char inputBuffStr[32]; 
char binaryBuffer[17];
char* binString;

void newSBPCommand();
char* int2bin(int value, char* buffer, int bufferSize);


int main() {

   SBPTest.attach(&newSBPCommand);          //interrupt to catch input

   while(1) { }
}


void newSBPCommand() {

    FILE* WriteTo = fopen("/local/log1.txt", "a");

    while (SBPTest.readable()) {
        //signal readable
        inputBuff[i] = SBPTest.getc(); 
        //fputc(inputBuff[i], WriteTo);
        binString = int2bin(inputBuff[i], binaryBuffer, 17);
        fprintf (WriteTo, "%s\n", binString);
        inputBuffStr[i] = *binString;
        i++;
    }

    fprintf(WriteTo," Read input once. ");

    inputBuffStr[i+1] = '[=14=]';

    //fwrite(inputBuff, sizeof inputBuffStr[0], 32, WriteTo);
    fclose(WriteTo);  

    MyFunc(inputBuffStr);

}




char* int2bin(int value, char* buffer, int bufferSize)
{
    //..................
}

我在 mbed 上编程,LPC1768。 main.cpp 和 typeFind.cpp 中都使用了序列号。我查看了堆栈溢出并推荐了 common.h 文件,但我遇到了编译器错误。

您不能在 header 中定义变量,否则您最终会在包含 header 的所有翻译单元中定义它,这违反了一个定义规则。只声明它:

// common.h
extern RawSerial SBPTest;

并且只在一个源文件中定义:

// common.cpp (or any other, but exactly one source file)
RawSerial SBPTest(USBTX, USBRX);

我建议使用列表初始化或复制初始化,因为直接初始化语法与函数声明不明确,可能会使不知道 USBTXUSBRX 是类型还是值的人感到困惑:

// common.cpp (or any other, but exactly one source file)
RawSerial SBPTest{USBTX, USBRX};        // this
auto SBPTest = RawSerial(USBTX, USBRX); // or this