简体   繁体   中英

make file is throwing below two error

Hello i have created four file fn.cpp header.h,main.cpp and makefile I am getting two error plz help to fix it.

  1. fn.cpp:1 error: string was not declared in this scope? why?

  2. fn.cpp:2 error :expected ',' or ';' before '{' token?

header.h:

#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int fn(string);

main.cpp:

#include "header.h"
string s= " hello world";
int main()
{
    fn(s):
}

fn.cpp:

int fn(string ss)
{
    printf("%s",ss);
}

makefile:

all:hello
hello:main.o fn.o
tab   g++ main.o fn.o-o hello
main.o:main.cpp
tab  g++ -c main.cpp
fn.o:fn.cpp
tab g++ -c fn.cpp

The std::string class is defined in the <string> header. Include that instead of the C library's <string.h> header.

Also, you need to include "header.h" from both source files.

Finally, you can't pass a string object directly to printf ; that's a C function which knows nothing of C++ classes. Either use C++ I/O:

std::cout << ss;

or faff around with C-style strings:

printf("%s", ss.c_str());

many small "out of c++ style" problems :)

use header #include <string> and avoid printf if you can, better use cout

c++ lovers would like this a little bit more:

fn.h

#include<string>
void fn(const std::string&);

fn.cpp

#include <stdio.h>
#include "fn.h"

void fn(const std::string& ss)
{
    printf(ss.c_str());
}

hello.cpp

#include "fn.h"

std::string s = " hello world";

int main()
{
    fn(s);
}

Makefile

all: hello

hello: hello.cpp fn.o

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM