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

问题描述 投票:1回答:1

我收到以下错误:“符号SBPTest乘法定义(通过../../build/typeFind.LPC1768.o和../../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] = '\0';

    //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文件,但是我遇到编译器错误。

c++ api mbed lpc
1个回答
1
投票

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

// 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
© www.soinside.com 2019 - 2024. All rights reserved.